【问题标题】:Working with substr_count() and arrays in PHP在 PHP 中使用 substr_count() 和数组
【发布时间】:2014-09-09 02:35:29
【问题描述】:

所以我需要将字符串与数组进行比较(字符串作为干草堆,数组作为针),并从字符串中获取在数组中重复的元素。为此,我采用了一个示例函数,在 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() 造成的,但我该如何绕过呢?我想搜索整个字符串匹配,而不是部分匹配。

【问题讨论】:

  • 我需要匹配整个单词作为一个元素。

标签: php arrays substring


【解决方案1】:

您可以将$haystack 分解为单个单词,然后在执行substr_count() 之前对其进行in_array() 检查以确保该单词作为整个单词存在于该数组中:

$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% 确定你为什么需要使用数组作为针,但也许你可以在函数外部做一个循环,如果需要的话,为每个针调用它 - 无论如何只是另一种选择!

【讨论】:

  • 是的,解决了。感谢您分配的时间。将尽快接受答案。
【解决方案2】:

只是把我的解决方案扔在这里;正如 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_reduce() 步骤基本上是这样的:

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

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

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 2012-05-09
    • 2011-05-01
    • 1970-01-01
    • 2011-05-05
    • 2011-01-01
    相关资源
    最近更新 更多