为了找到字符串中最后一个单词的长度,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')."\n");
print_r("The length of the last word is ");
print_r(last_word_len('this is a sample')."\n");
?>
输出结果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;
}
根据位置找到字符串的子字符串,并找到该字符串的长度并作为输出返回。在此函数之外,对于两个不同的样本,通过传递参数来调用该函数,并将输出打印在屏幕上。