The levenshtein() function in PHP 8.5 calculates the minimum number of character insertions, replacements, or deletions needed to transform one string into another. It remains fully supported, and since PHP 8.0, it no longer has the previous 255-character limit restriction.
Function Signature
levenshtein(
string $string1,
string $string2,
int $insertion_cost = 1,
int $replacement_cost = 1,
int $deletion_cost = 1
): int
Parameters
→$string1 / $string2: The two strings being compared.
→$insertion_cost / $replacement_cost / $deletion_cost: Optional costs for each operation (default is 1 for all). Adjusting these allows the algorithm to favor certain transformations.
Example: Spell Check Suggestion
A common use case is finding the closest matching word from a list (e.g., for a "Did you mean?" feature).
<?php
$input = carrrot ;
$words = [ apple , pineapple , banana , orange , radish , carrot , pea , bean , potato ];$shortest = -1;
foreach ($words as $word) {
$lev = levenshtein($input, $word);// Exact match found
if ($lev == 0) {
$closest = $word;
$shortest = 0;
break;
}// Find the closest match so far
if ($lev <= $shortest || $shortest < 0) {
$closest = $word;
$shortest = $lev;
}
}echo "Input word: $input ";
if ($shortest == 0) {
echo "Exact match found: $closest ";
} else {
echo "Did you mean: $closest? ";
}
?>
Output:
Input word: carrrot
Did you mean: carrot?