微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP库用于解析类似Google的搜索运算符?

我想创建一个 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

从那以后我可以为数据库构建搜索功能.

您可以从 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"
}

原文地址:https://www.jb51.cc/php/132176.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐