PHP strpos 匹配大海捞针

标签 php arrays match strpos

我想检查 $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(不要问为什么)。

最佳答案

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

$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 进行比较,否则你会错过句子开头的匹配项。

关于PHP strpos 匹配大海捞针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757217/

相关文章:

php - 代码和 SQL 查询中有什么错误?为什么网页上没有任何显示?

php - switch 语句中的正则表达式

c - C 中缺少数组数据

Mysql REGEXP 'o' 或 'aw'

regex - 如何在 Vim 中的每一行末尾添加一个字符串?

sql - 在数据库列中查找和匹配

php 数组和 str_replace 一起工作

php - 无法在 Eloquent/Query Builder 中使用多个占位符

python - Numpy:具有积分限制的数值积分

java - 如何检查包含字符串的数组是否包含另一个字符串数组中的某些单词