PHP – 如何使用 mb_substr_count() 计算子字符串的数量?
phpserver side programmingprogramming
在 PHP 中,我们可以使用函数 mb_substr_count() 计算给定字符串中子字符串的总数。
语法
int mb_substr_count(str $haystack, str $needle, str $encoding)
参数
mb_substr_count() 接受三个参数:$haystack、$needle 和 $encoding。
$haystack− 此参数将检查字符串。
$needle−此参数用于指示子字符串是否从给定的总字符串中被找到。
$encoding− 此参数是字符编码。如果不存在或为空,则使用内部字符编码值。
返回值
这将返回needle子字符串在haystack字符串中出现的次数。
示例
<?php // 使用mb_substr_count函数 $string= mb_substr_count("This is a test", "is"); echo "$string"; ?>
输出
2