1

我正在为我的 PHP 网站创建搜索服务,我想知道其他人如何根据引号(以及将来可能的其他符号)智能地解析搜索词。

换句话说,搜索词螺丝刀锤子可能会产生 ['screwdriver', 'hammer'] 的数组,但“平头螺丝刀”锤子可能会产生 ['flathead screwdriver', 'hammer']。

我知道我可以在一个草率的循环中完成这个,但我确信 PHP 有内置的东西来处理这个。

4

2 回答 2

1

尝试使用preg_split

就像是:

/* $search_term:
*  "flathead screwdriver" hammer -nails
*/

$terms = preg_split("/[\s]*\\\"([^\\\"]+)\\\"[\s]*|[\s]+/", $search_term);

/* $terms = array(
*      0    =>    "flathead screwdriver"
*      1    =>    "hammer"
*      2    =>    "-nails"
*/

$exclude = array();

foreach($terms as $term){
    if(strpos($term, '-') == 0)
        array_push($exclude, substr($term, 1));
}

/* $exclude = array(
*      0    =>    "nails"
*/

我唯一没有包括的是从 $terms 数组中删除“钉子”。我将把它作为练习留给读者=)

于 2010-10-05T16:57:01.730 回答
0

根据上一篇文章,我最终使用了strtok

于 2010-10-05T20:48:57.547 回答