如何从数组中获取最重要的事件?

How to get most important occurrences from an array?

首先,这不是特定于语言的问题,下面的示例使用了 PHP,但更多的是关于寻找答案的方法(正则表达式?)。

假设我有一个数组:

$array = ['The Bert and Ernie game', 'The Bert & Ernie game', 'Bert and Ernie game', 'Bert and Ernie game - english version', 'Bert & Ernie (game)', 'Bert and Ernie - game'] etc...

我想获取显示最重要组合的组合。所以我想做:

$magicPattern = [something that renders most important occurrences];
preg_match($magicPattern, $array, $matches);
print_r($matches);

作为输出,我希望收到如下内容:"Bert and Ernie game"

PS: 我没有必要寻找实际的数组,这样做的概念也很棒。

更新:
下面的当前代码,如果这是找到事件的最佳版本的好方法,有什么想法吗?很难从函数的 source 中找出它。

$array['The Bert and Ernie game']               =0; //lev distance
$array['The Bert & Ernie game']                 =0; //lev distance
$array['Bert and Ernie game']                   =0; //lev distance
$array['Bert and Ernie game - english version'] =0; //lev distance
$array['Bert & Ernie (game)']                   =0; //lev distance
$array['Bert and Ernie - game']                 =0; //lev distance

foreach($array as $currentKey => $currentVal){
    foreach($array as $matchKey => $matchVal){
        $array[$currentKey] += levenshtein($currentKey, $matchKey);
    }
}

$array = array_flip($array);
ksort($array);

echo array_values($array)[0]; //Bert and Ernie game

您需要一些东西来查看每个值并计算数值权重,然后根据权重对数组进行排序并取最上面的项目。

权重是您的 "importance",因此您可以选择为您认为更重要的术语分配更高的权重。

有许多不同的解决方案可以解决这样的问题,我个人不建议为此使用正则表达式。这通常是您可以使用全文搜索索引解决的问题(只需 google 全文搜索的许多方法即可完成此操作)。

对于这种特殊情况,假设您没有太多数据,您可以只计算 Levenshtein 距离:http://php.net/manual/en/function.levenshtein.php

或使用similar_text()函数:http://php.net/manual/en/function.similar-text.php