PHP similar_text() Function (original) (raw)

Last Updated : 23 Sep, 2024

The similar_text() function is a built-in function in PHP. This function calculates the similarity of two strings and returns the number of matching characters in the two strings. The function operates by finding the longest first common sub-string and repeating this for the prefixes and the suffixes, recursively. The sum of lengths of all the common sub-strings is returned. It can also calculate the similarity of the two strings in percent. The function calculates the similarity in percent, by dividing the result by the average of the lengths of the given strings times 100.

**Syntax :

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

**Parameters:

This function accepts three parameters as shown in the above syntax out of which the first two must be supplied and the last one is optional. All of these parameters are described below:

**Return Value :

**Example:

Input: string1="code",string1 = "code", string1="code",string2 = "coders
Output : 4 (80 %)

Input: string1="hackers",string1 = "hackers", string1="hackers",string2 = "hackathons"
Output: 5 (58.823529411765 %)

Examples of PHP similar_text() Function

Below programs illustrate the similar_text() function:

**Example 1: Finding Similarity Between Two Strings

In this example, we use the similar_text() function to calculate the number of similar characters between two strings, and also calculate the similarity percentage.

php `

sim=similartext("hackers","hackathons",sim = similar_text("hackers", "hackathons", sim=similartext("hackers","hackathons",percent); // To display the number of matching characters echo "Number of similar characters : $sim\n"; // To display the percentage of matching characters echo "Percentage of similar characters : $percent\n"; ?>

`

**Output:

Number of similar characters : 5
Percentage of similar characters : 58.823529411765>

Example 2: Case-Sensitivity of the similar_text() Function

This example highlights that the similar_text() function is case-sensitive. It compares two strings where the case of characters is the same, resulting in a high similarity percentage.

php `

`

**Output:

Number of similar characters : 13
Percentage of similar characters : 86.666666666667

**Example 3: Importance of the Order of Strings

In this example, we will show that the order of the strings passed to similar_text() matters. Changing the order of strings can result in different numbers of similar characters.

php `

`

**Output:

Number of similar characters : 2
Number of similar characters : 3