【问题标题】:PHP strpos match all needles in multiple haystacksPHP strpos匹配多个干草堆中的所有针
【发布时间】:2015-04-29 16:50:15
【问题描述】:

我想检查 $words 中的所有单词是否存在于一个或多个 $sentences 中,单词顺序并不重要。

单词将只包含 [a-z0-9]。

句子将只包含 [a-z0-9-]。

到目前为止,我的代码几乎可以按预期工作:

$words = array("3d", "4");
$sentences = array("x-3d-abstract--part--282345", "3d-speed--boat-430419", "beautiful-flower-462451", "3d-d--384967");

foreach ($words as $word) {
    $sentences_found = array_values(array_filter($sentences, function($find_words) use ($word) {return strpos($find_words, $word);}));
}
print_r($sentences_found);

如果你在这里运行这段代码 http://3v4l.org/tD5t5 ,你会得到 4 个结果,但实际上应该是 3 个结果

Array
(
    [0] => x-3d-abstract--part--282345
    [1] => 3d-speed--boat-430419
    [2] => beautiful-flower-462451   // this one is wrong, no "3d" in here, only "4"
    [3] => 3d-d--384967
)

我该怎么做?

还有比 strpos 更好的方法吗?

正则表达式?

正则表达式对于这项工作可能很慢,因为有时会有 1000 条 $sentences(不要问为什么)。

【问题讨论】:

  • 嗯?我运行你的代码,print_r() 的结果是:Array ( [0] => this-is-simple-simple-sentence-123-aa99-311qwerty ) 而不是 3 个项目
  • 你确定吗?我用 print_r() 得到所有 3 个结果
  • @Sunny 也为我工作! (见:3v4l.org/b2AoN
  • 我想我需要重新检查我的代码,我向您展示的这段代码只是更大代码的一部分,有些东西干扰了我的结果:) 至少这段代码按预期工作: )
  • 好的,我只在我的服务器上测试了这段代码,它运行良好,所以我回答了我自己的问题,然后哈哈

标签: php arrays match strpos


【解决方案1】:

您可以对每个单词使用找到的句子的交集:

$found = array();

foreach ($words as $word) {
    $found[$word] = array_filter($sentences, function($sentence) use ($word) {
        return strpos($sentence, $word) !== false;
    });
}

print_r(call_user_func_array('array_intersect', $found));

或者,从$sentences接近:

$found = array_filter($sentences, function($sentence) use ($words) {
    foreach ($words as $word) {
        if (strpos($sentence, $word) === false) {
            return false;
        }
    }
    // all words found in sentence 
    return true;
});

print_r($found);

要提到的重要一点是您的搜索条件错误;而不是strpos($sentence, $word),你应该明确比较false,否则你会错过句子开头的匹配。

【讨论】:

  • 出色的工作! tyvm 效果很好,我尝试了各种组合,一切都很好,我会给你有史以来最大的支持! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 2012-05-22
  • 2011-08-02
  • 2011-06-16
  • 2012-03-19
  • 1970-01-01
相关资源
最近更新 更多