我想创建一个PHP搜索功能,但是使用类似Google的运算符。例如:
these words "this phrase" location:"Los Angeles" operator:something
像location这样的运算符非常重要:支持带有空格的值(因此这个例子中的引号),所以我不能只是拆分或使用标准令牌。我想有人在某个时候创建了一个用于执行此操作的库,但我找不到任何库。
或者如果它不需要库,那么这样做的好方法就是好的。
这只是解析我需要的搜索查询;即从上面的查询中得到一个由以下内容组成的数组是可以的:
[0] => these
[1] => words
[2] => "this phrase"
[3] => location:"Los Angeles"
[4] => operator:something
由此我可以为数据库构建搜索功能。
答案 0 :(得分:12)
您可以从str_getcsv()开始并使用空格作为分隔符,但您可能需要预先处理该位置&运算符处理该特定情况下的引号。
<?php
$str = 'these words "this phrase" location:"Los Angeles" operator:something';
// preprocess the cases where you have colon separated definitions with quotes
// i.e. location:"los angeles"
$str = preg_replace('/(\w+)\:"(\w+)/', '"${1}:${2}', $str);
$str = str_getcsv($str, ' ');
var_dump($str);
?>
输出
array(5) {
[0]=>
string(5) "these"
[1]=>
string(5) "words"
[2]=>
string(11) "this phrase"
[3]=>
string(20) "location:Los Angeles"
[4]=>
string(18) "operator:something"
}