PHP 8 reference · String Functions
PHP similar_text() Function
Calculate how similar two strings are, as a count of matching characters and optionally as a percentage.
PHP 8 Since 4.0
Syntax
similar_text(string $string1, string $string2, float &$percent = null): int
Parameters
| Parameter | Description |
|---|---|
string1 |
The first string. |
string2 |
The second string. |
percent optional |
Set to the similarity as a percentage. |
Return value
The number of matching characters.
Examples
<?php
echo similar_text("World", "Word"), "\n";
similar_text("World", "Word", $percent);
echo round($percent, 1), "%\n";
Output
4 88.9%
<?php
similar_text("bafoobar", "barfoo", $a);
similar_text("barfoo", "bafoobar", $b);
echo round($a, 1), " vs ", round($b, 1), "\n"; // argument order can matter
Output
71.4 vs 42.9
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
levenshtein()· Calculate the edit distance between two strings: the fewest insertions, deletions and replacements to turn one into the other.soundex()· Return a four-character code for how an English word sounds, so names like Robert and Rupert can be matched.- PHP Strings · tutorial