How to parse user search string for Postgresql query?

浪子不回头ぞ 提交于 2020-01-14 04:08:57

问题


i created a search engine on my site using full text search in Postegresql. i added a searchbox in my PHP page in which users can write strings like these:

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

how to convert them to the following strings?

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

i tried several solutions but none works with all cases. The last one i tried is the following:

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

回答1:


Try this:

$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);

This will give:

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


来源:https://stackoverflow.com/questions/30760625/how-to-parse-user-search-string-for-postgresql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!