What is the similar_text() method of strings in PHP?

Overview

A string is a data type in PHP. We can assign the contents in a string variable by using double ("") or single quotation marks (''), like this:

$stringVar = "A string 5 v$%ariable";

Any character, except a few, can be saved in the stringVar string variable as long as it is enclosed in either single or double quotation marks.

There are numerous methods to carry different actions on string variables. Among these is the similar_text() method.

What is the similar_text() method in PHP?

This built-in method in PHP is used to compare two strings and to calculate the degree of similarity between them.

Syntax

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

Parameters

  • $string1 and $string2 represent the two strings that are to be compared.

Note: Placing $string1 before $string2 may not give the same result as when we place $string2 before $string1.

  • $percent is the third argument. It is seen as a reference. When this argument is passed, it causes similar_text() to calculate the percentage of similarity, by dividing the result of the similar_text() method by the average of the lengths of the given strings, multiplied by 100. The similarity percentage of the two strings is stored in the variable that is passed in this argument. This is an optional parameter. We can skip it if we want.

Return value

After the comparison, it returns the number of matched characters in both strings.

This is calculated by finding the longest first common substring for the prefixes and the suffixes, recursively. The lengths of all the common substrings that are found are added.

Code

Let’s do similarity calculations for some strings.

<?php
// a string variable
$fruit = "mango";
$percentage = 0;
$sim = similar_text($fruit, 'maggot');
echo "similarity: $sim ($percentage%)\n";
// check similarity
$sim = similar_text($fruit, 'maggot', $percentage);
//percentage similarity saved in $percentage is echoed.
echo "similarity: $sim ($percentage%)\n";
$sim = similar_text('barfoo', 'bafoobar', $percentage);
echo "similarity: $sim ($percentage%)\n";
// now swap the the strings used above
$sim = similar_text('bafoobar', 'barfoo', $percentage);
echo "similarity: $sim ($percentage%)\n";
//now check out the difference.
?>

Explanation

In line 5, we can see that we don’t use the third argument. However, in line 8, we can see that the similar_text() method updates the value of $percentage.

We can see how swapping the positions of the barfoo and bafoobar strings in line 11 and line 14 change the output of the code.

Note: This function uses a special algorithm, which calculates similarity based on the substrings. It starts with the longest matching substring and checks for other matching substrings to the left and right of the longest matching substring.

This method is supported by PHP version 4 and above.

Free Resources