【问题标题】:Using REGEX to parse a search string with boolean operators使用 REGEX 解析带有布尔运算符的搜索字符串
【发布时间】:2012-12-04 02:05:01
【问题描述】:

我找到了这个答案 - https://stackoverflow.com/a/7943464/1901367 - 这给了我这个非常有用的代码,让我可以解析包含引号和空格的搜索字符串。

preg_match_all('/(?<!")\b\w+\b|(?<=")\b[^"]+/', $subject, $result, PREG_PATTERN_ORDER);

我想知道是否有人可以告诉我如何更改此代码,以使 + 和 - 等布尔运算符保持不变,因为当前代码将它们删除。

我想使用这些运算符对我的数据库进行全文布尔搜索,但我对这个我不理解的正则表达式感到困惑。

示例输入和输出。

输入:'"this is some" text here is -more -"exlude me"' 输出:[this is some] [text] [here] [is] [-more] [-exclude me] 这些将在 $result 数组中

因此,由空格分隔的所有内容都是单独的项目,除非它是用“”括起来的短语。这已经有效,但是在我有 -more 和 -"exlude me" 的地方,当前的结果将是 [more] 和 [exclude me] 丢失我想要保留的减号。

提前致谢!

【问题讨论】:

  • 请提供示例输入以及这些输入的预期输出。
  • 完成,我已将其添加到问题中

标签: php regex string parsing search


【解决方案1】:

您无法使用正则表达式捕获“-exclude me”,因为匹配项始终是连续的。充其量,您可以修改正则表达式以匹配“-more”标记:

(?&lt;!")-?\b\w+\b|(?&lt;=")\b[^"]+

【讨论】:

    【解决方案2】:

    您可以使用简单的正则表达式提取标记,包括引号和其中的所有内容,然后在使用它们之前对其进行美化。像这样的:

    function query_tokens($query)
    {
        $regex = '/-?"[\pL\s]+"|-?\pL+/';
    
        preg_match_all($regex, $query, $tokens, PREG_SET_ORDER);
    
        foreach ($tokens as & $token)
        {
            $token = array_shift($token);
    
            $modifier = NULL;
    
            if ($token[0] === '-' || $token[0] === '+')
            {
                $modifier = $token[0];
    
                $token = substr($token, 1);
            }
            if ($token[0] === '"')
            {
                $token = trim($token, '"');
            }
            $token = $modifier.$token;
        }
    
        return $tokens;
    }
    

    使用的字符串和函数的结果:

    var_dump(query_tokens('"this is some" text here is -more -"exlude me"'));
    array (size=6)
      0 => string 'this is some' (length=12)
      1 => string 'text' (length=4)
      2 => string 'here' (length=4)
      3 => string 'is' (length=2)
      4 => string '-more' (length=5)
      5 => string '-exlude me' (length=10)
    

    正则表达式很棒,但有时它们会使事情变得比需要的更复杂。

    【讨论】:

    • 谢谢,我稍后试试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2011-01-30
    • 2013-02-09
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多