substr_count()函数是PHP中用来计算字符串中指定子串出现的次数的函数。该函数的语法如下:
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
其中,参数$haystack表示被搜索的字符串,参数$needle表示被搜索的子串,参数$offset表示开始搜索的位置,参数$length表示需要搜索的字符串长度。
substr_count()函数会返回字符串中指定子串出现的次数,如果指定子串不存在,则返回0。
使用示例
例如,字符串"Hello World"中,"l"出现的次数为3,则可以使用如下代码计算:
$str = "Hello World"; $count = substr_count($str, "l"); echo $count; // 3
也可以指定搜索的字符串长度和开始搜索的位置,如:
$str = "Hello World"; $count = substr_count($str, "l", 6, 5); echo $count; // 1
以上代码中,指定开始搜索的位置为6,搜索的字符串长度为5,只会搜索字符串"World","l"出现的次数为1。