【问题标题】:Searching keywords from one array against values of another array - php根据另一个数组的值从一个数组中搜索关键字 - php
【发布时间】:2017-08-23 11:53:54
【问题描述】:

我有 2 个数组。一个带有错误的关键字,另一个带有站点名称。

$bad_keywords = array('google', 
                      'twitter', 
                      'facebook');

$sites = array('youtube.com', 'google.com', 'm.google.co.uk', 'walmart.com', 'thezoo.com', 'etc.com');

简单任务:我需要过滤$sites 数组并过滤out 包含$bad_keywords 数组中找到的任何关键字的任何值。最后,我需要一个包含干净值的数组,我根本不会发现任何 bad_keywords 发生。

我已经在网上搜索过,似乎找不到一个简单的解决方案。以下是我尝试过的几种方法:
1. 使用 2 个foreach 循环(感觉更慢 - 我认为使用内置 php 函数会加快速度)
2.array_walk
3.array_filter

但我还没有找到最好、最有效的方法。我想要一个工具,可以过滤 20k+ 个站点的列表,并针对可能长达 1k 长的关键字列表进行过滤,因此性能至关重要。此外,在这种情况下,实际搜索的更好方法是什么 - regexstrpos

还有哪些其他选择可以做到这一点,最好的方法是什么?

【问题讨论】:

  • 你的预期输出
  • @ArunKumaresh 输出:过滤后的 $sites 数组(即不包含在其值中找到 bad_keyword 的任何元素)

标签: php arrays regex sorting strpos


【解决方案1】:

使用preg_grep函数的短解:

$result = preg_grep('/'. implode('|', $bad_keywords) .'/', $sites, 1);
print_r($result);

输出:

Array
(
    [0] => youtube.com
    [3] => walmart.com
    [4] => thezoo.com
    [5] => etc.com
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多