CancelImage Upload

Calculating the similarity between two strings in PHP

This tutorial will discuss how you can calculate the similarity of two strings in PHP. The returned value will be the match percentage, ideal therefore for search functions where results only need be displayed with a 50% plus match.

The function we will be using is PHP's own similar_text(). As so often with programming little development is required from the developers side, once he or she knows which functions to use to fulfil the task.

To start of, all we need is two strings that are relatively similar:

<?php

$string1 = "This will be our first string.";

$string2 = "And this will be our second string!";

...

We can then compare the two strings with similar_text():

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

And then for the finishing touch round of $percentage and print it out:

...

echo "Similarities are at: ".round($percentage, 2)."%";

?>

And that is all there is to it. If you add it all up you get the following code:

<?php

$string1 = "This will be our first string.";

$string2 = "And this will be our second string!";

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

echo "Similarities are at: ".round($percentage, 2)."%";

?>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com