我的挑战在以下示例中解释:给出了关键字组合“游戏笔记本”。
我想检查两个关键字是否出现在字符串中。挑战是字符串看起来像这样:
“漂亮的游戏笔记本” “游戏笔记本” “极端游戏笔记本”
我希望我的函数对所有三个字符串都返回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";
}
答案 0 :(得分:0)
您希望在数据库中使用类似CMU Sphinx或自然语言索引的内容。 (参见http://dev.mysql.com/doc/refman/5.7/en/fulltext-natural-language.html)快速搜索php库“nlp-tools / nlp-tools”,但是,我从未使用纯php解决方案来完成你想要做的事情。
答案 1 :(得分:0)
使用preg_match_all
和array_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";
}
答案 2 :(得分:0)
<?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));
答案 3 :(得分:0)
componentWillMount: function () {
window.MyVars = {
ajax: require('../helpers/ajax.jsx'),
utils: require('../helpers/utils.jsx')
};
}
当2个关键字出现在字符串中时,按任意顺序并且最多相隔4个字时,这将显示OK。
<强>解释强>
$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";
}