Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP similar_text() function

Reference for PHP similar_text(): count matching characters between two strings and get a percentage similarity, with argument order effects and limits.

similar_text() measures how alike two strings are. It returns the number of matching characters and, through a by-reference third argument, a similarity percentage.

The algorithm finds the longest common substring, then repeats the search on the parts to the left and right of it, adding up the lengths. The result is case-sensitive and depends on argument order in some cases.

PHP
<?php
echo similar_text("World", "Word");  // 4

Try it

PHP Matches and percentage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Suggesting the closest word

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
similar_text(string $string1, string $string2, float &$percent = null): int
Name Description
$string1 The first string.
$string2 The second string.
&$percent Optional. Receives the similarity as a percentage: matches * 2 / (len1 + len2) * 100.

Return value: the number of matching characters.

Usage notes

  • Percentage formula: it is twice the match count divided by the sum of the lengths. Two empty strings give 0.
  • Argument order matters in some cases because the algorithm picks the first longest common substring it finds. Test both orders if the result matters.
  • Case-sensitive. Lowercase both inputs for a case-insensitive score.
  • Performance: the time grows roughly with the cube of the length in the worst case, so avoid very long strings (thousands of characters).
  • Bytes, not characters, so multibyte text gives odd scores.
  • Alternatives: levenshtein() counts edit operations and is usually better for typo detection; soundex() and metaphone() compare sounds.