PHP similar_text() Function
The PHP similar_text() function calculates the similarity between two strings. It can also calculate the similarity of the two strings in percent.
Note: The levenshtein() function is faster than this function. However, this function gives more accurate result with less modifications needed.
Syntax
similar_text(string1, string2, percent)
Parameters
string1 |
Required. Specify the first string. |
string2 |
Required. Specify the second string. Please note that swapping string1 with string2 will yield different result. |
percent |
Required. By passing a reference as third argument, the function will calculate the similarity in percent. This is achieved by dividing the result of similar_text() by the average of the lengths of the given strings times 100. |
Return Value
Returns the number of matching chars in both strings.
The number of matching characters is calculated by finding the longest first common substring, and then doing this for the prefixes and the suffixes, recursively. The lengths of all found common substrings are added.
Example:
The example below shows the usage of similar_text() function.
<?php $str1 = "Hello World"; $str2 = "Hello Marry"; echo "Similarity: ".similar_text($str1, $str2)."\n"; echo "Similarity: ".similar_text($str2, $str1)."\n"; ?>
The output of the above code will be:
Similarity: 7 Similarity: 7
Example:
Consider one example where the third parameter is passed to calculate the similarity in percentage.
<?php $str1 = "Hello World"; $str2 = "Hello Marry"; $sim = similar_text($str1, $str2, $p); echo "Similarity: $sim ($p %)"; ?>
The output of the above code will be:
Similarity: 7 (63.636363636364 %)
❮ PHP String Reference