PHP substr_count() 函数:统计字符串中指定文本出现的次数
可以使用 PHP 内置函数 substr_count() 来搜索指定文本在字符串中出现的次数。
函数语法:substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int
参数说明:
$haystack:要搜索的字符串。$needle:要搜索的文本。$offset:可选参数,从哪个位置开始搜索,默认为 0。$length:可选参数,指定搜索的长度。如果未指定,则搜索整个字符串。
函数返回值:
返回指定文本在字符串中出现的次数。
示例代码:
$str = 'Hello World. This is a test string.';
$search = 'is';
$count = substr_count($str, $search);
echo "The text '{$search}' appears {$count} times in the string.";
输出结果:
The text 'is' appears 2 times in the string.
原文地址: https://www.cveoy.top/t/topic/kpwy 著作权归作者所有。请勿转载和采集!