【问题标题】:How to parse user search string for Postgresql query?如何解析 Postgresql 查询的用户搜索字符串?
【发布时间】:2015-06-10 15:21:22
【问题描述】:

我在我的网站上使用 Postegresql 中的全文搜索创建了一个搜索引擎。 我在我的 PHP 页面中添加了一个搜索框,用户可以在其中编写如下字符串:

word1 +word2
word1+word2
word1    -word2
 word1-word2
word1 word2
word1  word2

如何将它们转换为以下字符串?

word1&word2
word1&word2
word1&!word2
word1&!word2
word1|word2
word1|word2

我尝试了几种解决方案,但没有一个适用于所有情况。 我尝试的最后一个如下:

    $user_query_string = trim($_GET['search']);
    $final_query_string = str_replace(array('+', ' ', '-'), array('&','|', '&!'), $user_query_string);

【问题讨论】:

    标签: php postgresql parsing full-text-search logical-operators


    【解决方案1】:

    试试这个:

    $a=array('word1 +word2','word1+word2','word1    -word2',' word1-word2','word1 word2','word1  word2');
    
    foreach ($a as &$v) {
      $v=preg_replace('/ +/','|',        // last: change blanks to |
         preg_replace('/ *(?=[!&])/','', // delete blanks before ! or &
         strtr(trim($v),array('-'=>'&!','+'=>'&'))  // turn + and - into & and !&
         ));
    }
    print_r($a);
    

    这将给出:

    Array
    (
        [0] => word1&word2
        [1] => word1&word2
        [2] => word1&!word2
        [3] => word1&!word2
        [4] => word1|word2
        [5] => word1|word2
    )
    

    【讨论】:

    • 工作正常!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2023-02-15
    • 2013-07-27
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多