PHP 8 reference · String Functions

PHP levenshtein() Function

Calculate the edit distance between two strings: the fewest insertions, deletions and replacements to turn one into the other.

PHP 8 Since 4.0

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

Syntax

levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int

Parameters

ParameterDescription
string1 The first string.
string2 The second string.
insertion_cost optional Cost of inserting a character. Default: 1
replacement_cost optional Cost of replacing a character. Default: 1
deletion_cost optional Cost of deleting a character. Default: 1

Return value

The distance as an int.

Examples

Edit distanceTry it yourself
<?php
echo levenshtein("kitten", "sitting"), "\n";
echo levenshtein("php", "php"), "\n";

Output

3
0
Did you mean…?Try it yourself
<?php
$words = ["apple", "banana", "orange"];
$input = "banaan";
$best = null;
foreach ($words as $word) {
    $d = levenshtein($input, $word);
    if ($best === null || $d < $best[1]) {
        $best = [$word, $d];
    }
}
echo "Did you mean {$best[0]}?\n";

Output

Did you mean banana?

Version history

VersionChange
PHP 4.0Added
PHP 8.0Strings of any length are accepted (the old limit was 255 bytes).

Was this page helpful?