PHP 程式查詢字串中最後一個單詞的長度


若要查詢字串中最後一個單詞的長度,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;
}

基於位置的字串子字串被找到,並且該字串的長度被找出來並作為輸出返回。在此功能之外,透過傳遞引數呼叫該函式,對於兩個不同的樣本,輸出被列印在螢幕上。

更新於:17-Aug-2020

864 次檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.