Length of last word php

Last update on August 19 2022 21:50:29 (UTC/GMT +8 hours)

PHP Challenges - 1: Exercise-24 with Solution

Input : PHP Exercises

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

Explanation :

Length of last word php

Sample Solution :

PHP Code :

<?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 String   

Flowchart:

Length of last word php

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find majority element in an array.
Next: Write a PHP program to find the single number which occurs odd number of times and other numbers occur even number of times.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

PHP: Tips of the Day

PHP: Pass a PHP string to a JavaScript variable (and escape newlines)

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

Ref : https://bit.ly/34f0Dym


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation


View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    We are given a string. We are required to write a program in PHP to find the length of the last word in the string using inbuilt functions. We have already discussed approach of solving this problem here. This article discusses the PHP solution to the problem. Examples:

    Input : "php exercises" 
    Output : 9
    
    Input : "geeks for geeks"
    Output : 5

    We will mainly use these three inbuilt function in PHP to solve this problem:

    • substr() Function: This inbuilt function in PHP is used to extract a part of string.
    • strrpos() Function: This inbuilt function in PHP is used to find the last position of string in original or in another string. It returns the integer value corresponding to position of last occurrence of the string, also it treats uppercase and lowercase characters uniquely.
    • strlen() Function: This inbuilt function in PHP is used to find the length of a string.

    The idea to solve this problem using the above mentioned inbuilt function is to first find the position of last occurring space in the string using the strrpos() function. After getting the position of last occurring space we can easily get the last word in the string using the substr() function and store this in a new string variable. At last, we can use the strlen() function to find the length of the last word in the string. 

    PHP

    <?php

        function length_last_word($string)

        {  

            $pos = strrpos($string, ' ');

            if(!$pos)

            {

                $pos = 0;

            }

            else

            {

                $pos = $pos + 1;

            }

            $lastWord = substr($string,$pos);

            return strlen($lastWord);

        }

        print_r(length_last_word('geeksforgeeks')."\n");

        print_r(length_last_word('computer science portal')."\n");

    ?>

    Output:

    13
    6

    How can I get the last word of a string in PHP?

    The strrpos() function finds the position of the last occurrence of a string inside another string.

    How do you find the length of a word in a string?

    Java String length().
    Signature. The signature of the string length() method is given below: public int length() ... .
    Specified by. CharSequence interface..
    Returns. Length of characters. In other words, the total number of characters present in the string. ... .
    Internal implementation. public int length() { return value.length;.

    How do I count words in PHP?

    PHP str_word_count() Function.
    Count the number of words found in the string "Hello World!": echo str_word_count("Hello world!"); ... .
    Return an array with the words from the string: ... .
    Return an array where the key is the position of the word in the string, and value is the actual word: ... .
    Without and with the char parameter:.

    How do I cut a string after a specific character in PHP?

    The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.