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')."
");
print_r("The length of the last word is ");
print_r(last_word_len('this is a sample')."
");
?>输出
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;
}基于位置的字符串子字符串被找到,并且该字符串的长度被找出来并作为输出返回。在此功能之外,通过传递参数调用该函数,对于两个不同的样本,输出被打印在屏幕上。
广告
数据结构
网络化
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP