计算字符串中的 php 数组出现次数


Counting php array occurrences in a string

我有一个字符串和一个值数组,我想检查数组中的项目在字符串中出现的次数。

这是最快的方法吗?

$appearsCount = 0;
$string = "This is a string of text containing random abc def";
$items = array("abc", "def", "ghi", "etc");
foreach($items as $item)
{
    $appearsCount += substr_count($string, $item);
}
echo "The item appears $appearsCount times";
您可能会

发现正则表达式很有用:

$items = array('abc', 'def', 'ghi', 'etc');
$string = 'This is a string of text containing random abc def';
$appearsCount = count(preg_split('/'.implode('|', $items).'/', $string)) - 1;

当然,您必须注意不要使正则表达式无效。(即,如果$items中的值在正则表达式的上下文中包含特殊字符,则需要正确转义这些值。

这与多个子字符串计数并不完全相同,因为基于正则表达式的拆分不会对重叠项目进行两次计数。

最快,可能 - 至少你不太可能通过任意输入获得更快的速度。但是,请注意,您可能并不完全正确:

$appearsCount = 0;
$string = "How many times is 'cac' in 'cacac'?";
$items = array("cac");
foreach($items as $item)
{
    $appearsCount += substr_count($string, $item);
}
echo "The item appears $appearsCount times";