php 查找字符串中最后一个,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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值