The `levenshtein()` function in PHP calculates the Levenshtein distance between two strings, which represents the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.PHP 8. PHP 8.1,PHP 8.2,PHP 8.3,and PHP 8.4.
Basic Syntax<?phplevenshtein(string $string1,string $string2,int $insertion_cost = 1,int $deletion_cost = 1,int $replacement_cost = 1): int?>
Example with Custom CostsYou can specify different costs for insertions, deletions, and substitutions:
<?php$string1 = "Saturday";$string2 = "Sunday";// Standard calculation$standard = levenshtein($string1, $string2);// With custom costs (higher cost for substitutions)$custom = levenshtein($string1, $string2, 1, 1, 2);echo "Standard distance: $standard\n"; // Output: 3echo "Custom distance: $custom\n"; // Output: 5?>
Notes1. The function is case-sensitive. "Hello" and "hello" will have a distance of 1.2. For very long strings, consider using `similar_text()` which may be faster (though it measures similarity differently).3. The maximum string length is 255 characters. For longer strings, the function returns -1.The `levenshtein()` function is particularly useful for spell checking, search suggestions, and natural language processing tasks.