在PHP中,字符串函数 substr_count() 用来计算子串出现的次数。
函数语法:
substr_count ( string $str , string $substr [, int $start = 0 [, int $len ]] ) : int
函数参数说明:
| 参数 | 描述 |
|---|---|
| str | 必需。规定要检查的字符串。 |
| substr | 必需。规定要检索的字符串。 |
| start | 可选。规定在字符串中何处开始搜索。 |
| len | 可选。规定搜索的长度。 |
substr_count() 函数计算子串出现的次数。需要注意的是:
1. 子串是区分大小写的。
2. 该函数不计数重叠的子串。
3. 如果 start 参数加上 length 参数大于字符串长度,该函数则生成一个警告
举例1,计算子串出现的次数:
<?php
// 计算子串出现的次数
$res = substr_count('this is a island.', 'is');// 输出
echo $res;;
以上代码输出如下:
3
举例2,计算子串出现的次数(指定start):
<?php
// 计算子串出现的次数,指定start
$res = substr_count('this is a island.', 'is', 5);// 输出
echo $res;
以上代码输出如下:
2
举例3,计算子串出现的次数(指定start,start + len超出字符串长度):
<?php
// 计算子串出现的次数,指定start,len
$res = substr_count('this is a island.', 'is', 5, 20);// 输出
echo $res;
以上代码输出如下警告:
Warning: substr_count(): Length value 20 exceeds string length
举例4,计算子串出现的次数(不计数重叠的子串):
<?php
// 计算子串出现的次数,不计算重叠
$res = substr_count('this isisis a island.', 'isis');// 输出
echo $res;
以上代码输出如下:
1