我正在尝试编写一个搜索查询,以便从数据库中找到文章。我想使用用户输入的搜索字符串,并寻找一组特定的可能的搜索词。如果用户输入搜索字符串“2011年德国的平均工资列表”,我想生成一个搜索条件列表。我想我会找出整个字符串和连续单词的部分字符串。也就是说,我想找的是“平均工资清单”和“2011年德国”,而不是“2011年德国上市”。
到目前为止,我有一些代码来生成我的搜索词:
$searchString = "listing of average salaries in germany for 2011";
$searchTokens = explode(" ", $searchString);
$searchTerms = array($searchString);
$tokenCount = count($searchTokens);
for($max=$tokenCount - 1; $max>0; $max--) {
$termA = "";
$termB = "";
for ($i=0; $i < $max; $i++) {
$termA .= $searchTokens[$i] . " ";
$termB .= $searchTokens[($tokenCount-$max) + $i] . " ";
}
array_push($searchTerms, $termA);
array_push($searchTerms, $termB);
}
print_r($searchTerms);它给了我一系列的条件:
我不知道该如何得到缺少的条件:
更新
我不是在寻找“电源集”,所以像this或this这样的答案是无效的。例如,我不希望这些内容出现在我的术语列表中:
我只想找连续的单词。
发布于 2013-06-21 17:12:24
您想要找到已爆炸字符串的所有顺序子集,只需从offset=0开始,然后用length=1将数组拆分到count-offset。
$search_string = 'listing of average salaries in germany for 2011';
$search_array = explode(' ',$search_string);
$count = count($search_array);
$s = array();
$min_length = 1;
for ($offset=0;$offset<$count;$offset++) {
for ($length=$min_length;$length<=$count-$offset;$length++) {
$match = array_slice($search_array,$offset,$length);
$search_matches []= join(' ',$match);
}
}
print_r($search_array);
print_r($search_matches);发布于 2013-06-20 19:07:19
首先,我只想让您知道,如果要在SQL数据库上运行所有这些以进行搜索,这是非常低效率的,因此建议您使用LIKE选项。http://www.techonthenet.com/sql/like.php
现在,要获得所有可能的组合,只需将这些单词分解成一个数组(就像您已经做过的那样),并遵循@ulvund关于这个问题的建议:PHP: How to get all possible combinations of 1D array?
也就是说
<?php
$array = explode(" ", "listing of average salaries in germany for 2011");
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
?>https://stackoverflow.com/questions/17221648
复制相似问题