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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

similar_text(string $string1, string $string2, float &$percent = null): int

Parameters

ParameterDescription
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

Similarity scoreTry it yourself
<?php
echo similar_text("World", "Word"), "\n";
similar_text("World", "Word", $percent);
echo round($percent, 1), "%\n";

Output

4
88.9%
Order can change the resultTry it yourself
<?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

VersionChange
PHP 4.0Added

Was this page helpful?