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 送给学长毕业祝福语简短