我正在尝试编写搜索查询以从数据库中查找文章。我想获取用户输入的搜索字符串并查找一组特定的可能搜索词。如果用户输入搜索字符串“2011 年德国平均工资列表”,我想生成一个要搜索的术语列表。我想我会寻找整个字符串和连续单词的部分字符串。也就是说,我想搜索“listing of average salaries”和“germany for 2011”,而不是“listing germany 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);
它给了我这个术语列表:
- 2011 年德国平均工资列表
- 列出德国的平均工资
- 2011 年德国平均工资的百分比
- 德国平均工资列表
- 2011 年德国平均工资
- 平均工资列表
- 2011 年德国的工资
- 列出平均工资
- 2011 年在德国
- 列出平均值
- 2011 年德国
- 列表
- 2011 年
- 上市
- 2011
我不确定如何获得缺少的条款:
- 在德国的平均工资为
- 德国的平均工资
- 德国的平均工资
- 平均工资在
- 德国的平均工资
- 在德国的工资
- 等...
更新
我不是在寻找“电源组”,所以像 this 这样的答案或 this无效。例如,我不希望这些出现在我的术语列表中:
- 普通德国
- 列出 2011 年的薪水
- 德国
我只查找连续的单词。
最佳答案
你想找到分解字符串的所有顺序子集,只需从 offset=0
开始并将数组拆分为 length=1
直到 count-偏移量
:
$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);
关于php - 将字符串解析成部分,只有连续的单词,而不是幂集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221648/