Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用正则表达式解析带有布尔运算符的搜索字符串_Php_Regex_String_Parsing_Search - Fatal编程技术网

Php 使用正则表达式解析带有布尔运算符的搜索字符串

Php 使用正则表达式解析带有布尔运算符的搜索字符串,php,regex,string,parsing,search,Php,Regex,String,Parsing,Search,我找到了这个答案- -这给了我这个非常有用的代码,允许我解析包含引号和空格的搜索字符串 preg_match_all('/(?<!")\b\w+\b|(?<=")\b[^"]+/', $subject, $result, PREG_PATTERN_ORDER); preg_match_all('/(?您可以使用一个简单的正则表达式来提取带有引号和其中所有内容的标记,然后在使用它们之前对它们进行整理。类似于以下内容: function query_tokens($query) {

我找到了这个答案- -这给了我这个非常有用的代码,允许我解析包含引号和空格的搜索字符串

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

preg_match_all('/(?您可以使用一个简单的正则表达式来提取带有引号和其中所有内容的标记,然后在使用它们之前对它们进行整理。类似于以下内容:

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)

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

您不能使用正则表达式捕获“-exclude me”,因为匹配总是连续的。您最多可以修改正则表达式以匹配“-more”标记:


(?请提供示例输入以及这些输入的预期输出。完成后,我已将其添加到问题中。谢谢,我稍后将尝试此功能