我正在编写一个基本的分类工具,它将获取一个标题,然后将其与一组关键字进行比较。示例:
$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/