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
Syntax
levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int
Parameters
| Parameter | Description |
|---|---|
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
<?php
echo levenshtein("kitten", "sitting"), "\n";
echo levenshtein("php", "php"), "\n";
Output
3 0
<?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
Related
similar_text()· Calculate how similar two strings are, as a count of matching characters and optionally as a percentage.soundex()· Return a four-character code for how an English word sounds, so names like Robert and Rupert can be matched.- PHP Strings · tutorial