所以我需要的是将字符串与数组进行比较(字符串作为大海捞针,数组作为针) 并从字符串中获取在数组中重复的元素。为此,我在 substr_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()
造成的,但我该如何绕过它呢?我想搜索整个字符串匹配项,而不是部分匹配项。
最佳答案
您可以将 $haystack
分解成单个单词,然后执行 in_array()
检查它以确保该单词作为一个完整单词存在于该数组中在执行您的 substr_count()
之前:
$animals = array('cat','dog','bird', 'cat', 'dog', 'bird', 'bird', 'hello');
$toString = implode(' ', $animals);
$data = array('cat');
function substr_count_array($haystack, $needle){
$initial = 0;
$bits_of_haystack = explode(' ', $haystack);
foreach ($needle as $substring) {
if(!in_array($substring, $bits_of_haystack))
continue; // skip this needle if it doesn't exist as a whole word
$initial += substr_count($haystack, $substring);
}
return $initial;
}
echo substr_count_array($toString, $data);
Here, cat
is 2, dog
is 2, bird
is 3, hello
is 1 and lion
is 0.
编辑:这是使用 array_keys()
的另一种选择将搜索参数设置为 $needle
:
function substr_count_array($haystack, $needle){
$bits_of_haystack = explode(' ', $haystack);
return count(array_keys($bits_of_haystack, $needle[0]));
}
当然,这种做法需要以绳子为针。我不是 100% 确定为什么你需要使用数组作为针,但也许你可以在函数外部做一个循环,并在需要时为每根针调用它 - 无论如何只是另一种选择!
关于php - 在 PHP 中使用 substr_count() 和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24816808/