将字符串解析为部分,仅解析连续的单词,而不是幂集

时间:2013-06-20 18:59:15

标签: php string-parsing

我正在尝试编写搜索查询以从数据库中查找文章。我想获取用户输入的搜索字符串,并查找一组特定的搜索字词。如果用户输入搜索字符串“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);

它给了我这个术语列表:

  • 2011年德国平均工资列表
  • 列出德国的平均工资
  • 2011年德国平均工资
  • 德国平均工资列表
  • 2011年德国的平均工资
  • 中的平均工资列表
  • 2011年德国的工资
  • 平均工资列表
  • 2011年在德国
  • 平均列表
  • 2011年德国
  • 的列表
  • for 2011
  • 列出
  • 2011

我不确定如何获得缺少的条款:

  • 在德国的平均工资
  • 德国平均工资
  • 德国的平均工资
  • 的平均工资
  • 德国的平均工资
  • 德国的工资
  • 等...

更新

我不是在寻找“电源设置”,因此thisthis等答案无效。例如,我不希望在我的术语列表中使用这些:

  • 普通德国
  • 上市工资2011
  • of germany for

我正在寻找连续的单词。

2 个答案:

答案 0 :(得分:0)

首先,我只想告诉您,如果要针对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);

?>

答案 1 :(得分:0)

您想要查找爆炸字符串的所有连续子集,只需从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);