PHP 字符串计算 strlen、strpos 与 strrpos 函数
墨初 后端开发 3664阅读
今天无聊一直逛PHP的论坛,顺便弄点有用的东西保存下来,正好很多时间没有更新博客了,今天说说PHP中一些字符串计算的函数,如果我说的不对,还请大神们在下方的评论处留言,并指正一二。
计算字符串的长度或定位字符串出现的位置。
相关函数如下:

strlen():取得字符串的长度
strpos():定位字符串第一次出现的位置
strrpos():定位字符串最后一次出现的位置
strlen()

strlen() 函数用于取得字符串的长度,返回一个整型。
语法:
string substr( string string )
例子: <?php echo strlen('abc def');//输出 7 echo strlen('ab北京');//输出 6 ,UTF-8编码下输出 8 ?>
strpos()

strpos() 函数用于定位字符串第一次出现的位置,返回整型。
语法:
int strpos ( string string, mixed needle [, int start] )
参数说明如下:
参数说明
string要处理的字符串
needle要定位的字符串
start可选,定位的起始位置
例子:
<?php echo strpos('abcdef', 'c');//输出 2 ?>
strrpos()
strrpos() 函数用于定位字符串最后一次出现的位置,返回整型。
语法:
int strpos ( string string, mixed needle [, int start] ) strrpos() 函数用法与 strpos() 类似,只不过 strrpos() 用于取得指定字串最后出现的位置。
例子:
<?php $str = "This function returns the last occurance of a string"; $pos = strrpos($str, "st"); if($pos !== FALSE){ echo '字串 st 最后出现的位置是:',$pos; } else { echo '查找的字符串中没有 in 字串'; } ?>
运行该例子,浏览器输出:
字串 st 最后出现的位置是:46