PHP 程序查找字符串中最后一个单词的长度

phpserver side programmingprogramming更新于 2025/8/23 3:07:17

要查找字符串中最后一个单词的长度,PHP 代码如下 −

示例

<?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')."
");    print_r("The length of the last word is ");    print_r(last_word_len('this is a sample')."
"); ?>

输出

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

定义了一个名为 ‘last_word_len’ 的 PHP 函数,该函数接受一个字符串作为参数 −

function last_word_len($my_string)
{
//
}

使用 ‘strrpos’ 函数查找另一个字符串中第一次出现空格的位置。如果该位置存在,则赋值为 0。否则,加 1。 −

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

根据位置查找字符串的子字符串,并计算该字符串的长度并将其作为输出返回。在此函数外部,通过传递参数调用该函数,针对两个不同的示例,并将输出打印在屏幕上。


相关文章