php - 在少数情况下拆分文本 (PHP)

标签 php mysql sql

我有一个表单输入字段“文本”,我想根据用户在该字段中输入的值创建不同的查询

  1. 如果只有一个短语 - 搜索每个词(例如“Hello World”):

    SELECT (...) WHERE x LIKE '%Hello%' AND x LIKE '%World%' etc...
    
  2. 如果短语在引号中 - 搜索整个短语(例如 '"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/

相关文章:

sql - 如何比较 SQL Server 中的时间?

php - 通过 REST Drupal 8.x 更新用户密码

php - 多连接Mysql

php - PHP 和 MySQL 中的访问策略

php - 使用 PHP 将 CSV 加载到 MySQL 表中

mysql - 父类别中的总计数记录

sql - 在 SQL DB 中查询列中的特定字符串

sql - 如何从前 50 名中随机选择 8 首具有唯一 user_id 的歌曲?

php - 类型转换和与松散运算符的比较 "=="

PHP/HTML - 没有登录但来自导航链接的个人资料页面