PHP strpos匹配多个干草堆中的所有指针

阳光明媚

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

单词将仅包含[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的$句子(不要问为什么)。

插口

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

$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,否则您将在句子开头错过匹配项。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章