要计算一个字符串中某个子串出现的次数,可以使用PHP的substr_count()函数。
substr_count()函数的语法如下:
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
参数说明:
示例代码:
$str = "Hello, PHP is a popular language. PHP is easy to learn.";
$subStr = "PHP";
$count = substr_count($str, $subStr);
echo "子串出现的次数为:" . $count;
输出结果:
子串出现的次数为:2
以上代码中,$str是要搜索的字符串,$subStr是要搜索的子串,substr_count()函数返回子串出现的次数,最后将结果输出。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站