【发布时间】:2018-10-11 16:06:37
【问题描述】:
我正在尝试创建一个搜索字符串,它可以接受这样的查询:
$string = 'title -launch category:technology -tag:news -tag:"outer space"$';
下面是我想要做的快速解释:
$ = suffix indicating that the match should be exact
" = double quotes indicate that the multi-word is taken as a single keyword
- = a prefix indicating that the keyword is excluded
这是我当前的解析器:
$string = preg_replace('/(\w+)\:"(\w+)/', '"${1}:${2}', $string);
$array = str_getcsv($string, ' ');
我之前使用过上面的代码,但是对于以 -tag:"outer space" 等搜索开头的关键字,它不能按预期工作。上面的代码无法识别以 - 字符开头的字符串,并在 outer 和 space 之间的空白处断开关键字,尽管用双引号括起来。
编辑:我试图用该代码做的是 preg_replace -tag:"outer space" 到 "-tag:outer space" 这样当我将字符串传递给 str_getcsv() 时它们不会被破坏.
【问题讨论】:
-
试试
(\w+):"([^"]+)"或(\w+):(?|"([^"]+)"|(\S+)) -
我尝试将两者都放在 preg_replace() 的第一个参数上,但它们仍然做同样的事情,将 -tag:"outer space" 分解为 -tag:outer 和空间。
-
我不确定,因为我是新手,但我认为问题从 str_getcsv() 开始,因为尽管被引用,它仍在尝试将空格上的关键字分成两个。我需要它通过包含 - 字符来工作。这意味着正则表达式没有正确地将术语括在 str_getcsv() 的引号中。
-
为什么要使用
str_getcsv?使用preg_match_all -
我明白了,抱歉,我误解了这个问题。试试regex101.com/r/iuHyFq/3,见PHP demo