Php 将字符串解析为多个部分,仅分析连续的单词,而不是幂集
我正在尝试编写一个搜索查询,从数据库中查找文章。我想获取用户输入的搜索字符串,并查找一组特定的可能搜索词。如果用户输入搜索字符串“2011年德国平均工资列表”,我想生成一个要搜索的术语列表。我想我会寻找整个字符串和连续单词的部分字符串。也就是说,我想搜索“平均工资清单”和“2011年德国”,但不是“2011年德国清单” 到目前为止,我有以下代码来生成搜索词:Php 将字符串解析为多个部分,仅分析连续的单词,而不是幂集,php,string-parsing,Php,String Parsing,我正在尝试编写一个搜索查询,从数据库中查找文章。我想获取用户输入的搜索字符串,并查找一组特定的可能搜索词。如果用户输入搜索字符串“2011年德国平均工资列表”,我想生成一个要搜索的术语列表。我想我会寻找整个字符串和连续单词的部分字符串。也就是说,我想搜索“平均工资清单”和“2011年德国”,但不是“2011年德国清单” 到目前为止,我有以下代码来生成搜索词: $searchString = "listing of average salaries in germany for 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);
$searchString=“2011年德国平均工资列表”;
$searchTokens=explode(“,$searchString”);
$searchTerms=数组($searchString);
$tokenCount=计数($searchTokens);
对于($max=$tokenCount-1;$max>0;$max--){
$termA=“”;
$termB=“”;
对于($i=0;$i<$max;$i++){
$termA.=$searchTokens[$i]。“”;
$termB.=$searchTokens[($tokenCount-$max)+$i]。“”;
}
数组推送($searchTerms,$termA);
array_push($searchTerms,$termB);
}
打印(搜索条款);
它给了我这个术语列表:
- 2011年德国平均工资清单
- 年德国平均工资清单
- 2011年德国平均工资的
- 德国平均工资清单
- 2011年德国的平均工资
- 年平均薪金表
- 2011年德国工资
- 平均薪金表
- 2011年在德国
- 平均价格表
- 2011年德国
- 上市
- 2011年
- 上市
- 2011年
- 年德国平均工资的
- 德国的平均工资
- 年德国平均工资
- 年平均工资
- 德国的平均工资
- 在德国的工资
- 等等
- 普通德国
- 2011年上市薪酬
- 德国
我只查找连续的单词。首先,我只想让您知道,如果您要对SQL数据库运行所有这些搜索,这是非常低效的,建议您使用
LIKE
选项
现在,要获得所有可能的组合,只需将单词分解成一个数组(就像您使用explode所做的那样),并遵循@ulvund给出的关于这个问题的建议:
也就是说
<?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);
?>
要查找分解字符串的所有顺序子集,只需从偏移量=0开始,并将数组拆分为长度=1
到计数偏移量
:
$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);
$search_string='2011年德国平均工资清单';
$search\u数组=分解(“”,$search\u字符串);
$count=count($search\u数组);
$s=数组();
$min_长度=1;
对于($offset=0;$offset,您正在寻找的称为电源集。在这里已经多次询问并解决了该问题。:)和。这种方法似乎效率低下,而且不必要地复杂。你可能应该看看Lucene或Sphinx之类的东西。