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

Ton*_*rix 2 php search

是否有一种简单的方法可以解析包含否定词的搜索词的字符串?

'this -that "the other thing" -"but not this" "-positive"' 
Run Code Online (Sandbox Code Playgroud)

会变成

array(
  "positive" => array(
    "this",
    "the other thing",
    "-positive"
  ),
  "negative" => array(
    "that",
    "but not this"
  )
)
Run Code Online (Sandbox Code Playgroud)

所以这些术语可以用来搜索.

cod*_*ken 5

下面的代码将解析您的查询字符串并将其拆分为正面和负面搜索字词.

// 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);
Run Code Online (Sandbox Code Playgroud)

产量

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

    [negative] => Array
        (
            [0] => that
            [1] => but not this
        )
)
Run Code Online (Sandbox Code Playgroud)