mb_substr_count
计算子字符串出现次数
PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8
mb_substr_count 函数用于统计在字符串中某个子字符串出现的次数。此函数是多字节字符串函数(mbstring)的一部分,专门用于处理多字节字符编码(如UTF-8)。
int mb_substr_count ( string $haystack , string $needle [, string $encoding = mb_internal_encoding() ] )
返回子字符串出现的次数。如果没有找到子字符串,则返回0。
<?php $str = "Hello world, hello PHP!"; $needle = "hello"; $count = mb_substr_count($str, $needle, "UTF-8"); echo $count; // 输出 2 ?>
在示例中,我们定义了一个包含 "Hello world, hello PHP!" 的字符串 `$str`,并使用 `mb_substr_count()` 来统计 "hello" 这个子字符串在其中出现的次数。结果输出2,因为"hello"在字符串中出现了两次(注意大小写)。