PHP检查字符串中是否出现两个关键字

PHP检查字符串中是否出现两个关键字,php,preg-match-all,Php,Preg Match All,我的challange在下面的示例中进行了解释:给出了关键字组合“gaming notebook” 我想检查这两个关键字是否出现在一个字符串中。挑战在于,字符串可能如下所示: “漂亮的游戏笔记本” “游戏笔记本” “极限游戏笔记本” 我希望我的函数为所有三个字符串返回true。在单词组合之间有3-4个单词的公差,如示例所示,如果切换关键字,我希望它能够工作 因此,我的方法如下,但似乎不起作用: $keyword = strtolower("gaming notebook"); $parts =

我的challange在下面的示例中进行了解释:给出了关键字组合“gaming notebook”

我想检查这两个关键字是否出现在一个字符串中。挑战在于,字符串可能如下所示:

“漂亮的游戏笔记本” “游戏笔记本” “极限游戏笔记本”

我希望我的函数为所有三个字符串返回true。在单词组合之间有3-4个单词的公差,如示例所示,如果切换关键字,我希望它能够工作

因此,我的方法如下,但似乎不起作用:

$keyword = strtolower("gaming notebook");
$parts = explode(" ", $keyword);

$string = strtolower("Which notebook for good gaming performance");
//point to end of the array
end($parts);
//fetch key of the last element of the array.
$lastElementKey = key($parts);
//iterate the array
$searchExpression = "";
foreach($parts as $k => $v) {
    if($k != $lastElementKey) {
        $searchExpression .= $v . "|";
    } else {
        $searchExpression .= $v;
    }
}

if(preg_match_all('#\b('. $searchExpression .')\b#', $string, $matches) > 0) {
    echo "Jep, keyword combination is in string";
} else {
    echo "No, keyword combination is not in string";
}

您希望在数据库中使用CMU Sphinx或自然语言索引之类的内容。(请参阅)快速搜索php库时出现了“nlp工具/nlp工具”,但是,我从未使用纯php解决方案来完成您试图完成的任务。

使用
preg\u match\u all
array\u intersect
函数的解决方案:

$keywordStr = "gaming notebook";
$string = "Which notebook for good gaming performance,it's my notebook";
$keywords = explode(" ", $keywordStr);
$parts = implode("|", $keywords);

preg_match_all("/\b$parts\b/i", $string, $matches);
// matched items should contain all needed keywords
if (count($keywords) == count(array_intersect($keywords, $matches[0]))) {
    echo "Jep, keyword combination is in string";
} else {
    echo "No, keyword combination is not in string";
}

当两个关键字以任意顺序出现在字符串中并且最多由4个单词分隔时,这将回显OK

说明:

/
(?::非捕获组
\b$kw1:关键字1
(?:\s+\w+{0,4}:后跟0到4个其他单词
\s+:空间(s)
$kw2\b:关键字2
)
|
(?::非捕获组
\b$kw2:关键字2
(?:\s+\w+{0,4}:后跟0到4个其他单词
\s+:空间(s)
$kw1\b:关键字1
)
/

公差是一项要求吗?嘿,Robbie,是的,即使两个关键字之间有一个或两个单词(或20个字符),它也应该返回true。谢谢Roman,现在它可以完美地检查字符串中是否有所有关键字。如果关键字之间不超过两个或三个单词,你知道脚本如何只能返回true吗。假设:“用于exreme游戏的笔记本”返回true,但“用于大量广泛游戏的笔记本”返回false。
<?php

$keyword = strtolower("gaming notebook");
$string = strtolower("Which notebooks for good gaming performance");
function check($keyword,$string){
    $parts = explode(' ',$keyword);
    $result = false;
    $pattern = implode('|',$parts);
    preg_match_all("(\b{$pattern}\b)",$string,$matches);
    if(isset($matches[0])){
       return true;
    }

    return false;
}

var_dump(check($keyword, $string));
$reg = "/(?:\b$kw1(?:\s+\w+){0,4}\s+$kw2\b)|(?:\b$kw2(?:\s+\w+){0,4}\s+$kw1\b)/";
if (preg_match($reg, $string)) {
    echo "OK\n";
} else {
    echo "KO\n";
}