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')."\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;
}根据位置找到字符串的子字符串,并找到该字符串的长度并作为输出返回。在此函数之外,对于两个不同的样本,通过传递参数来调用该函数,并将输出打印在屏幕上。
热门推荐
10 送你妹妹新婚祝福语简短
11 教育集团发展祝福语简短
12 开工小花束祝福语简短
13 空军婚礼祝福语简短
14 英语寄信祝福语范文简短
15 美人出嫁文案祝福语简短
16 毕业祝福语贺词大全简短
17 夏天出门防晒祝福语简短
18 幼儿篮球祝福语大全简短