PHP substr_count() 函数
示例
计算字符串中 "world" 出现的次数
<?php
echo substr_count("Hello world. The world is nice","world");
?>
自己动手试一试 »
substr_count() 函数计算子字符串在字符串中出现的次数。
注意: 子字符串区分大小写。
注意: 此函数不计算重叠的子字符串(参见示例 2)。
注意: 如果 start 参数加上 length 参数的值大于字符串长度,此函数将生成警告(参见示例 3)。
语法
substr_count(string,substring,start,length)
参数值
参数 | 描述 |
---|---|
string | 必需。指定要检查的字符串 |
substring | 必需。指定要搜索的字符串 |
start | 可选。指定在 string 中开始搜索的位置。如果为负数,则从字符串末尾开始计数 |
length | 可选。指定搜索的长度 |
技术详情
返回值 | 返回 substring 在 string 中出现的次数 |
---|---|
PHP 版本 | 4+ |
更新日志 | PHP 7.1 - length 参数可以是 0 或负数。 PHP 7.1 - start 参数可以是负数。 PHP 5.1 - 添加了 start 和 length 参数。 |
更多示例
示例
使用所有参数
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // 使用 strlen() 返回字符串长度
echo substr_count($str,"is")."<br>"; // "is" 在字符串中出现的次数
echo substr_count($str,"is",2)."<br>"; // 字符串现在缩减为 "is is nice"
echo substr_count($str,"is",3)."<br>"; // 字符串现在缩减为 "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // 字符串现在缩减为 "s i"
?>
自己动手试一试 »
示例
如果 start 和 length 参数超出字符串长度,此函数将输出警告
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
这将输出警告,因为 length 值超出了字符串长度(3+9 大于 12)
❮ PHP 字符串参考