在 PHP 中智能解析用户搜索词

发布于 2024-09-26 03:52:31 字数 270 浏览 0 评论 0原文

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

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

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

I am in the midst of creating a search service for my PHP website and I was wondering how others have gone about intelligently parsing search terms based on quotation marks (and possibly other symbols in the future).

In others words, the search term screwdriver hammer might yield an array of ['screwdriver', 'hammer'], but "flathead screedriver" hammer might yield ['flathead screwdriver', 'hammer'].

I know I can accomplish this in a sloppy loop, but I'm sure PHP has something built in to handle this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦回旧景 2024-10-03 03:52:31

尝试使用 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"
*/

我唯一没有这样做include 正在从 $terms 数组中删除“钉子”。我将把这个作为练习留给读者=)

Try using preg_split

Something like:

/* $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"
*/

Only thing I didn't include is removing "nails" from the $terms array. I'll leave this as an exercise for the reader =)

○闲身 2024-10-03 03:52:31

我最终按照上一篇文章使用了strtok

I ended up using strtok as per this Previous Post

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文