问题
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