Asaf
Asaf

Reputation: 557

Comparing two strings to get uniqueness percent

I'm looking for a sulotion. I have two strings that I need to compare one to each other and get the uniqueness percent.

For example:

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

Upvotes: 0

Views: 1358

Answers (3)

Develoger
Develoger

Reputation: 3998

Here you go, this code is based on similar_text() php function, as I can see it compares strings by letters not whole words, look at example:

<?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>

Here is live example:
http://simplestudio.rs/yard/percent/percent.php

Upvotes: 1

Vijay
Vijay

Reputation: 365

You can use similar_text()

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

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

If you are looking for performance critical solution then you need to use optimized algorithm (In most cases this is a good solution).

Upvotes: 0

dag
dag

Reputation: 130

There are a few linguistic functions in PHP which you can use.

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

As your question is missing details about the criteria for the uniqueness you have to check if one of these fulfills your needs.

Upvotes: 1

Related Questions