similar_text(): Comparing strings to get the percentage of similarity
Measure similarity between two strings
similar_text() returns the number of matching characters and can also write a similarity percentage to a third argument. It is useful for small, byte-oriented comparisons, not language-aware search. Its execution cost can be high on long strings.
$first = 'Plus2net PHP';$second = 'Plus2net Python';$matches = similar_text($first, $second, $percent);echoround($percent, 1); // Display the percentage to one decimal place
The PHP similar_text() function compares two strings and calculates the percentage of similarity between them. This function is useful for tasks like fuzzy matching, where you need to compare how closely two strings resemble each other.
Syntax
similar_text(string $string1, string $string2, float &$percent = null): int
$first: The first string to compare. $second: The second string to compare. $percent (optional): A variable passed by reference that holds the percentage of similarity between the two strings. Return Value: The function returns the number of matching characters between the two strings. When supplied, the by-reference third parameter receives the percentage; the function itself still returns an integer count.
Basic Example of similar_text()
Here, we compare two strings to find the number of matching characters.
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.