我有一个表单输入字段“文本”,我想根据用户在该字段中输入的值创建不同的查询
如果只有一个短语 - 搜索每个词(例如“Hello World”):
SELECT (...) WHERE x LIKE '%Hello%' AND x LIKE '%World%' etc...
如果短语在引号中 - 搜索整个短语(例如 '"Hello World"'):
SELECT (...) WHERE x LIKE '%Hello World%'
这很酷 - 我可以做到。
但是当我必须混合上述功能时,我的问题就开始了——所以 f.e.如果短语是“Hello World”my name is“John”——它应该像这样搜索:
SELECT (...)
WHERE x LIKE '%Hello%'
AND x LIKE '%World%'
AND x LIKE '%my name is%'
AND x LIKE '%John%'
您将如何实现此类功能并设法在 php 中做到这一点?
最佳答案
您可以使用 preg_match_all(...):
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);
这将产生:
Array
(
[0] => Array
(
[0] => Lorem
[1] => ipsum
[2] => "dolor sit amet"
[3] => consectetur
[4] => "adipiscing \"elit"
[5] => dolor
)
)
如您所见,它还考虑了带引号的字符串中的转义引号。
一个简短的解释:
" # match the character '"'
(?: # start non-capture group 1
\\ # match the character '\'
. # match any character except line breaks
| # OR
[^\\"] # match any character except '\' and '"'
)* # end non-capture group 1 and repeat it zero or more times
" # match the character '"'
| # OR
\S+ # match a non-whitespace character: [^\s] and repeat it one or more times
如果匹配 %22 而不是双引号,你会这样做:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);
可以查看this还有
关于php - 在少数情况下拆分文本 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574396/