Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP levenshtein() function

Reference for PHP levenshtein(): edit distance between two strings, custom insert, replace and delete costs, typo suggestions and byte-based limits.

levenshtein() returns the Levenshtein distance between two strings: the smallest number of single-character insertions, replacements and deletions needed to turn the first string into the second. A distance of 0 means the strings are identical.

It is the standard tool for "did you mean" suggestions and for fuzzy matching of short words.

PHP
<?php
echo levenshtein("kitten", "sitting");  // 3

Try it

PHP Edit distance

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 Custom costs and a suggestion helper

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
levenshtein(
    string $string1,
    string $string2,
    int $insertion_cost = 1,
    int $replacement_cost = 1,
    int $deletion_cost = 1
): int
Name Description
$string1 The string to start from.
$string2 The string to reach.
$insertion_cost Cost of inserting a character into $string1. Default 1.
$replacement_cost Cost of replacing a character. Default 1.
$deletion_cost Cost of deleting a character. Default 1.

Return value: the total cost of the cheapest sequence of edits.

Usage notes

  • No length limit since PHP 8.0. Older versions returned -1 for strings longer than 255 characters.
  • Case-sensitive. Lowercase both strings for case-insensitive matching.
  • Bytes, not characters. An accented UTF-8 letter counts as two bytes, so distances for non-ASCII text are inflated. Convert to single-byte characters (for example via mb_str_split() and your own function) when it matters.
  • Cost grows with length product. Comparing two strings of lengths m and n takes about m times n steps; it is fine for words, not for whole documents.
  • Swapping two neighbors costs 2, since there is no transposition operation (that would be Damerau-Levenshtein).
  • Choosing a threshold: a distance of 1 or 2 is typical for typo suggestions on words under ten letters; scale with word length for longer text.
  • Sound-alike matching is a different task; see soundex() and metaphone().