PHP 从字符串中获取搜索词数组 [英] PHP get array of search terms from string

查看:55
本文介绍了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"' 

将更改为

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);

输出

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

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

这篇关于PHP 从字符串中获取搜索词数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆