在PHP中使用substr_count()和数组

在PHP中使用substr_count()和数组,php,arrays,substring,Php,Arrays,Substring,所以我需要的是比较字符串和数组(字符串作为草堆,数组作为针),并从字符串中获取在数组中重复的元素。为此,我在substr\u count函数中使用了一个示例函数,将数组用作指针 $animals = array('cat','dog','bird'); $toString = implode(' ', $animals); $data = array('a'); function substr_count_array($haystack, $needle){ $initial = 0

所以我需要的是比较字符串和数组(字符串作为草堆,数组作为针),并从字符串中获取在数组中重复的元素。为此,我在
substr\u count
函数中使用了一个示例函数,将数组用作指针

$animals = array('cat','dog','bird');
$toString = implode(' ', $animals);
$data = array('a');

function substr_count_array($haystack, $needle){
     $initial = 0;
     foreach ($needle as $substring) {
          $initial += substr_count($haystack, $substring);
     }
     return $initial;
}

echo substr_count_array($toString, $data);

问题是,如果我搜索像“a”这样的字符,它将通过检查并验证为合法值,因为“a”包含在第一个元素中。因此,上述输出
1
。我想这是由于foreach()的
foreach()
造成的,但我如何绕过它呢?我想搜索整个字符串匹配,而不是部分匹配。

您可以将
$haystack
分解为单个单词,然后在数组()中执行
检查它,确保该单词作为整个单词存在于该数组中,然后再执行
子数组计数()


编辑:这里是另一个选择,使用将搜索参数设置为
$pinder

function substr_count_array($haystack, $needle){
    $bits_of_haystack = explode(' ', $haystack);
    return count(array_keys($bits_of_haystack, $needle[0]));
}

当然,这种方法需要一根线作为针。我不能100%确定为什么需要使用数组作为指针,但如果需要,也许可以在函数外执行一个循环,并为每个指针调用它-无论如何,这只是另一个选项

把我的解决方案扔到这里;正如scrowler所概述的那样,其基本思想是将搜索主题分解为单独的单词,以便您可以比较整个单词

function substr_count_array($haystack, $needle) 
{
    $substrings = explode(' ', $haystack);

    return array_reduce($substrings, function($total, $current) use ($needle) {
        return $total + count(array_keys($needle, $current, true));
    }, 0);
}
array\u reduce()
步骤基本上是这样的:

$total = 0;
foreach ($substrings as $substring) {
    $total = $total + count(array_keys($needle, $substring, true));
}
return $total;

array_keys()
表达式返回值等于
$substring
$needle
的键。该数组的大小是出现的次数。

我需要将整个单词作为一个元素进行匹配。是的,这就解决了问题。感谢分配的时间。我们将尽快接受答案。
$total = 0;
foreach ($substrings as $substring) {
    $total = $total + count(array_keys($needle, $substring, true));
}
return $total;