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

标签 php regex arrays

我正在编写一个基本的分类工具,它将获取一个标题,然后将其与一组关键字进行比较。示例:

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

是否有创造性的方法来遍历这些类别或查看哪个类别的匹配度最高?请注意,在 'dining' 数组中,我使用正则表达式来匹配 candy 一词的变体。我尝试了以下方法,但随着这些类别列表变得很长,我想知道这是否是最好的方法:

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

谢谢, 史蒂夫

编辑: 感谢@jmathai,我能够添加排名:

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

最佳答案

这可以通过一个循环完成。

为了提高效率,我会将 candy 和 candies 分成单独的条目。一个聪明的技巧是用一些标记替换匹配项。让我们使用 10 个#。

$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.\n";

关于php将字符串匹配到多个关键字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904393/

相关文章:

c++ - 二维数组的 Big-O 插入

php - 仅将 MySQL 输出的第一个单词大写

php - 在Openshift环境中,如何访问不同应用程序中的数据库?

php - PHP While 循环中的 MySQL 更新

java - Kotlin split with regex 工作不如预期

javascript - 变量未写入数组 - Javascript

php - 插入查询有时有效,但有时无效

javascript - 用于将字符串中单词的字符更改为下划线的正则表达式,第一个字符除外

java - java 中的正则表达式和 ISO-8859-1 字符集

c++ - 平均值、RMS 和过零数数组 c++