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;
}根据位置找到字符串的子字符串,并找到该字符串的长度并作为输出返回。在此函数之外,对于两个不同的样本,通过传递参数来调用该函数,并将输出打印在屏幕上。
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿