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

时间:2012-10-05 00:04:37

标签: php algorithm compare

我正在寻找解决方案。 我有两个字符串,我需要相互比较并获得唯一性百分比。

例如:

{
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%
}

3 个答案:

答案 0 :(得分:1)

您可以使用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

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

答案 1 :(得分:1)

在这里,这段代码基于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

答案 2 :(得分:0)

您可以使用similar_text()

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

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

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