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

PHPServer Side ProgrammingProgramming

To find the length of the last word in the string, the PHP code is as follows −

Example

 Live Demo

<?php
   function last_word_len($my_string){
      $position = strrpos($my_string, ' ');
      if(!$position){
         $position = 0;
      } else {
         $position = $position + 1;
      }
      $last_word = substr($my_string,$position);
      return strlen($last_word);
   }
   print_r("The length of the last word is ");
   print_r(last_word_len('Hey')."\n");
   print_r("The length of the last word is ");
   print_r(last_word_len('this is a sample')."\n");
?>

Output

The length of the last word is 3
The length of the last word is 6

A PHP function named ‘last_word_len’ is defined, that takes a string as the parameter −

function last_word_len($my_string)
{
   //
}

The first occurrence of the space inside another string is found by using the ‘strrpos’ function. If that position is present, it is assigned to 0. Otherwise, it is incremented by 1 −

$position = strrpos($my_string, ' ');
if(!$position){
   $position = 0;
} else{
   $position = $position + 1;
}

The substring of the string, based on the position is found, and the length of this string is found and returned as output. Outside this function, the function is called by passing the parameter, for two different samples and the output is printed on the screen.

raja
Published on 17-Aug-2020 15:28:50
Advertisements