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

时间:2014-10-31 22:03:34

标签: php search

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

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

会改为

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

所以这些术语可用于搜索。

2 个答案:

答案 0 :(得分: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);

输出

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

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

答案 1 :(得分:0)

对于那些寻找相同内容的人,我已经为PHP和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;
}