
substr_count()函数用于计算子串在字符串中出现的次数。
语法
substr_count(string,substring,start,length)
定义和用法
substr_count() 返回子字符串 substring 在字符串 string 中出现的次数。注意 substring 区分大小写。
返回值
函数返回整型。它返回子字符串在字符串中出现的次数。
参数
| 序号 | 参数与说明 |
|---|---|
| 1 | string 指定在此字符串中进行搜索。 |
| 2 | substring 用于指定要搜索的字符串 |
| 3 | start 它指定何时在字符串中开始搜索,开始计数的偏移位置。如果是负数,就从字符的末尾开始统计。 |
| 4 | length 它指定字符串的长度 |
在线示例
试试下面的实例,计算 "krishna" 在字符串中出现的次数:
<?php
//计算 "krishna" 在字符串中出现的次数
echo substr_count("sairamkrishna","krishna");
echo '<br>';
$text = 'This is a test';
echo strlen($text); // 14
echo '<br>';
echo substr_count($text, 'is'); // 2
echo '<br>';
// 字符串被简化为 's is a test',因此输出 1
echo substr_count($text, 'is', 3);
echo '<br>';
// 字符串被简化为 's i',所以输出 0
echo substr_count($text, 'is', 3, 3);
echo '<br>';
// 输出 1,因为该函数不计算重叠字符串
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcd');
echo '<br>';
// 因为 5+10 > 14,所以生成警告
echo substr_count($text, 'is', 5, 10);
?>测试看看‹/›输出结果
1 14 2 1 0 3 PHP Warning: substr_count(): Invalid length value in...