levenshtein()
levenshtein() — Calculate Levenshtein distance between two strings.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform string1 into string2. The complexity of the algorithm is O(m*n), where n and m are the length of string1 and string2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).
Signature
levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string1 | string | One of the strings being evaluated for Levenshtein distance. |
| $string2 | string | One of the strings being evaluated for Levenshtein distance. |
| $insertion_cost | int | Defines the cost of insertion. |
| $replacement_cost | int | Defines the cost of replacement. |
| $deletion_cost | int | Defines the cost of deletion. |
Return value
This function returns the Levenshtein-Distance between the two argument strings.
Example
A runnable snippet:
// input misspelled word $input = 'carrrot'; // array of words to check against $words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato'); // no shortest distance found, yet $shortest = -1; // loop through words to find the closest foreach ($words as $word) { // calculate the distance between the input word, // and the current word $lev = levenshtein($input, $word); // check for an exact match if ($lev == 0) { // closest word is this one (exact match) $closest = $word; $shortest = 0; // break out of the loop; we've found an exact match break; } // if this distance is less than the next found shortest // distance, OR if a next shortest word has not yet been found if ($lev <= $shortest || $shortest < 0) { // set the closest match, and shortest distance $closest = $word; $shortest = $lev; } } echo "Input word: $input\n"; if ($shortest == 0) { echo "Exact match found: $closest\n"; } else { echo "Did you mean: $closest?\n"; }
Output:
Input word: carrrot Did you mean: carrot?
Changelog
| Version | Change |
|---|---|
| 8.0.0 | Prior to this version, levenshtein() had to be called with either two or five arguments. |
| 8.0.0 | Prior to this version, levenshtein() would return -1 if one of the argument strings is longer than 255 characters. |
See also
soundex(), similar_text(), metaphone()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page levenshtein() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.