dplht39359 2011-02-05 00:57
浏览 396
已采纳

php匹配字符串到多个关键字数组

I'm writing a basic categorization tool that will take a title and then compare it to an array of keywords. Example:

$cat['dining'] = array('food','restaurant','brunch','meal','cand(y|ies)');
$cat['services'] = array('service','cleaners','framing','printing');
$string = 'Dinner at seafood restaurant';

Are there creative ways to loop through these categories or to see which category has the most matches? Note that in the 'dining' array, I have regex to match variations on the word candy. I tried the following, but with these category lists getting pretty long, I'm wondering if this is the best way:

$keywordRegex = implode("|",$cat['dining']); 
preg_match_all("/(\b{$keywordRegex}\b)/i",$string,$matches]);

Thanks, Steve

EDIT: Thanks to @jmathai, I was able to add ranking:

    $matches = array(); 
    foreach($keywords as $k => $v) {
        str_replace($v, '#####', $masterString,$count);
        if($count > 0){
            $matches[$k] = $count;
        }
    }
    arsort($matches);
  • 写回答

5条回答 默认 最新

  • dongmei2956 2011-02-05 04:20
    关注

    This can be done with a single loop.

    I would split candy and candies into separate entries for efficiency. A clever trick would be to replace matches with some token. Let's use 10 #'s.

    $cat['dining'] = array('food','restaurant','brunch','meal','candy','candies');
    $cat['services'] = array('service','cleaners','framing','printing');
    $string = 'Dinner at seafood restaurant';
    
    $max = array(null, 0); // category, occurences
    foreach($cat as $k => $v) {
      $replaced = str_replace($v, '##########', $string);
      preg_match_all('/##########/i', $replaced, $matches);
      if(count($matches[0]) > $max[1]) {
        $max[0] = $k;
        $max[1] = count($matches[0]);
      }
    }
    
    echo "Category {$max[0]} has the most ({$max[1]}) matches.
    ";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度