Q:

Write a PHP program to find the length of the last word in a string

0

Write a PHP program to find the length of the last word in a string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function length_of_last_word($s)
{
      
        if (strlen(trim($s)) == 0)
        {
            return "Blank String";
        }
        
        $words = explode(' ', $s);
        
        if (sizeof($words) >1)
        return strlen(substr($s, strrpos($s, ' ') + 1));
        else
        return "Single word";
        
        
}
print_r(length_of_last_word("PHP Exercises")."\n");
print_r(length_of_last_word("PHP")."\n");
print_r(length_of_last_word("")."\n");
print_r(length_of_last_word("  ")."\n");
?>

Sample Output:

9                                                           
Single word                                                 
Blank String                                                
Blank Strin

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now