在php中查找两个字符串之间的匹配率?

问题描述 投票:2回答:2

有谁能给我一个更好的方法(或者说是最喜欢的方法),用模糊逻辑来查找两个字符串之间的匹配率(即这两个字符串(例如:名字)在百分比方面的密切程度),有谁能帮我写代码吗?

php string string-comparison fuzzy-logic
2个回答
6
投票
$str1 = 'Hello';
$str2 = 'Hello, World!';
$percent;
similar_text($str1, $str2, $percentage);

http:/php.netmanualenfunction.similar-text.php。


4
投票

单词比较器

这里有一个基于字的比较,而不是基于字符的比较(通过字来比较人文本往往更有意义)。

function wordSimilarity($s1,$s2) {

    $wordsof = function($s) {
        $a=[];foreach(explode(" ",$s)as $w) if($w) $a[$w]=1;
        return $a;
    };

    $w1 = $wordsof($s1); if(!$w1) return 0;
    $w2 = $wordsof($s2); if(!$w2) return 0;

    $allWords = "";
    $allWords.= join("",array_keys($w1));
    $allWords.= join("",array_keys($w2));
    $totalLen = max(strlen($allWords),1);
    $charDiff = 0;

    foreach($w1 as $word=>$x) if(!isset($w2[$word])) $charDiff+=strlen($word);
    foreach($w2 as $word=>$x) if(!isset($w1[$word])) $charDiff+=strlen($word);

    return 1-($charDiff/$totalLen);

}

逻辑很简单:它在另一个字符串中寻找一个字符串中的每一个字,两种方式。 长字的权重更高。 它给你一个0和1之间的浮点值,其中1是总相似度。 你可能想在比较之前对字符串进行规范化处理--空格修剪,多个空格替换为一个,全部小写,去掉标点符号等等--但这严格来说并不属于比较逻辑本身。

一些测试。


    $test = "this is something you've never done before";

    wordSimilarity($test,"this is something you've never done before");     //  1.00
    wordSimilarity($test,"this is something");                              //  0.58
    wordSimilarity($test,"this is nothing you have ever done");             //  0.31
    wordSimilarity($test,"leave me alone with lorem ipsum");                //  0.00
    wordSimilarity($test,"before you do something you've never done");      //  0.84
    wordSimilarity($test,"never have i ever done this");                    //  0.44

© www.soinside.com 2019 - 2024. All rights reserved.