PHP: similar_text() function


The similar_text() function is used to calculate the number of similar characters between two strings.
The similar_text() function can also calculate the similarity of the strings in percent.


(PHP 4 and above)


similar_text(first_string, second_string, npercent) 


Name Description Required /
first_string The first input string. Required String
second_string The second input string. Required String
npercent Variable to store the percentage of similarity between the input strings. Optional Integer

Return value:

Returns the number of matching chars in both strings.

Value Type: Integer


echo "Comparing strings : 'Good Morning' and 'Good Evening'".'<br>';
echo 'No of similar characters : '.similar_text('Good Morning', 'Good Evening').'<br>';
similar_text('Good Morning', 'Good Evening', $similar_percent);
echo 'Similarity between two strings in  percentage : '. $similar_percent;


Comparing strings: 'Good Morning' and 'Good Evening'
No of similar   characters : 9
Similarity between two strings in  percentage : 75

View the example in the browser

See also

PHP Function Reference

Previous: sha1
Next: sprintf

PHP: Tips of the Day

PHP: Using str_replace so that it only acts on the first match?

Can be done with preg_replace:

function str_replace_first($from, $to, $content)
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

Ref : https://bit.ly/35SCuP8