dr6673999 2014-10-31 22:03
浏览 49
已采纳

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.

  • 写回答

2条回答 默认 最新

  • dpir3950 2014-10-31 22:40
    关注

    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
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题