比较两个字符串以获得唯一性百分比



>我正在寻找一个sulotion。我有两个字符串,我需要将它们彼此比较并获得唯一性百分比。

例如:

{
String A = "Hello"
String B = "Hello"
Uniqueness percent = 0%
}
{
String A = "Hello friend"
String B = "Hello mate"
Uniqueness percent = 50%
}
{
String A = "Hey"
String B = "Hello"
Uniqueness percent = 100%
}

PHP 中有一些语言函数可供您使用。

http://php.net/manual/en/function.levenshtein.php

http://www.php.net/manual/en/function.soundex.php

http://www.php.net/manual/en/function.similar-text.php

http://www.php.net/manual/en/function.metaphone.php

由于您的问题缺少有关唯一性标准的详细信息,因此您必须检查其中之一是否满足您的需求。

在这里,这段代码基于 similar_text() php 函数,正如我所看到的,它通过字母而不是整个单词比较字符串,看看示例:

<?php
    if(isset($_REQUEST["str_a"]) && isset($_REQUEST["str_b"])) {
        $str_a = $_REQUEST["str_a"];    
        $str_b = $_REQUEST["str_b"];    
        function compare_them($str_1, $str_2) {
            $str_1 = trim(strtolower($str_1));
            $str_2 = trim(strtolower($str_2));
            similar_text($str_1, $str_2, $percentage);
            $formated_percents = number_format($percentage);
            return $formated_percents; 
        }
        $calculated = compare_them($str_a, $str_b);
    }

?>
<form action="" method="get">
    string a: <input type="text" value="" name="str_a" />
    <br />
    string b: <input type="text" value="" name="str_b" />
    <br />
    <br />
    <input type="submit" value="submit" />
</form>
<h2>
<?php 
    if(isset($_REQUEST["str_a"]) && isset($_REQUEST["str_b"])) { 
        print "string a = " . $str_a . " <br />string b = " . $str_b . " <br />percents match = " . $calculated . "%"; 
    }
?>
</h2>

这是实时示例:
http://simplestudio.rs/yard/percent/percent.php

你可以使用 similar_text()

similar_text($string1,$string2,$percentage);
echo $percentage;

http://www.php.net/manual/en/function.similar-text.php

如果您正在寻找性能关键型解决方案,那么您需要使用优化的算法(在大多数情况下,这是一个很好的解决方案)。

最新更新