PHP从字符串中获取搜索项的数组

Is there an easy way to parse a string for search terms including negative terms?

'this -that "the other thing" -"but not this" "-positive"' 

would change to

array(
  "positive" => array(
    "this",
    "the other thing",
    "-positive"
  ),
  "negative" => array(
    "that",
    "but not this"
  )
)

so those terms could be used to search.

The code below will parse your query string and split it up into positive and negative search terms.

// parse the query string
$query = 'this -that "-that" "the other thing" -"but not this" ';
preg_match_all('/-*"[^"]+"|\S+/', $query, $matches);

// sort the terms
$terms = array(
    'positive' => array(),    
    'negative' => array(),
);
foreach ($matches[0] as $match) {
    if ('-' == $match[0]) {
        $terms['negative'][] = trim(ltrim($match, '-'), '"');
    } else {
        $terms['positive'][] = trim($match, '"');
    }
}

print_r($terms);

Output

Array
(
    [positive] => Array
        (
            [0] => this
            [1] => -that
            [2] => the other thing
        )

    [negative] => Array
        (
            [0] => that
            [1] => but not this
        )
)

For those looking for the same thing I have created a gist for PHP and JavaScript

https://gist.github.com/UziTech/8877a79ebffe8b3de9a2

function getSearchTerms($search) {
    $matches = null;
    preg_match_all("/-?\"[^\"]+\"|-?'[^']+'|\S+/", $search, $matches);

    // sort the terms
    $terms = [
        "positive" => [],
        "negative" => []
    ];
    foreach ($matches[0] as $i => $match) {
        $negative = ("-" === $match[0]);
        if ($negative) {
            $match = substr($match, 1);
        }
        if (($match[0] === '"' && substr($match, -1) === '"') || ($match[0] === "'" && substr($match, -1) === "'")) {
            $match = substr($match, 1, strlen($match) - 2);
        }
        if ($negative) {
            $terms["negative"][] = $match;
        } else {
            $terms["positive"][] = $match;
        }
    }

    return $terms;
}