腾讯云618限量抢购
  1. PHP+MySQL数据库教程
  2. PHP进阶教程
  3. ThinkPHP 3.0/3.1 教程

PHP 字符串计算 strlen、strpos 与 strrpos 函数

最后更新:2010-10-19 17:08阅读:31037

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

本章节内容共分 10 部分:
  1. 1. PHP 字符串输出 echo、print 与 printf 函数
  2. 2. PHP 字符串去除 trim、ltrim 与 rtrim 函数
  3. 3. PHP implode 函数:将数组元素组合为字符串
  4. 4. PHP 字符串获取 substr 与 strstr 函数
  5. 5. PHP 字符串计算 strlen、strpos 与 strrpos 函数
  6. 6. PHP 字符串 XHTML格式化显示 nl2br 与 htmlspecialchars 函数
  7. 7. PHP 字符串存储(转义) addslashes 与 stripslashes 函数
  8. 8. PHP 字符串分割 explode 与 str_split 函数
  9. 9. PHP 字符串替换 substr_replace 与 str_replace 函数
  10. 10. PHP 字符串处理
腾讯云618限量抢购