【问题标题】:PHP library for parsing Google-like search operators?用于解析类似 Google 的搜索运算符的 PHP 库?
【发布时间】:2013-02-17 22:31:07
【问题描述】:

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

由此我可以为数据库构建搜索功能。

【问题讨论】:

标签: php search


【解决方案1】:

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

【讨论】:

  • 嗯,这给了我以下数组:[0] => 这些,[1] => 单词,[2] => 这个短语,[3] => 位置:“Los,[ 4] => 洛杉矶", [5] => 运算符:某事
  • 我指出需要预处理逻辑。我添加了一个简单的预处理正则表达式。
  • 太棒了!这真的很好用,正是我想要的。
  • 如果可以,我会吻你。我讨厌正则表达式。永远无法记住这些模式。现在我必须处理 GLOB。呃...这让我避免了花时间尝试编写正确的正则表达式。谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2012-10-27
  • 2017-09-20
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2019-05-07
相关资源
最近更新 更多