PHP levenshtein() Function
The PHP levenshtein() function calculates Levenshtein distance between two strings.
The Levenshtein distance is defined as the minimal number of characters that need to replace, insert or delete to transform string1 into string2. By default, PHP gives equal weight to each operation (replace, insert, and delete). However, the cost of each operation can be defined by setting the optional insertion_cost, replacement_cost, and deletion_cost parameters. The algorithm adapts to choose the cheapest transforms, i.e. if insertion_cost + deletion_cost < replacement_cost, no replacements is done, but rather insertions and deletions instead.
Syntax
levenshtein(string1, string2, insertion_cost, replacement_cost, deletion_cost)
Parameters
string1 |
Required. Specify the first string being evaluated for Levenshtein distance. |
string2 |
Required. Specify the second string being evaluated for Levenshtein distance. |
insertion_cost |
Optional. Specify the cost of inserting a character. Default is 1. |
replacement_cost |
Optional. Specify the cost of replacing a character. Default is 1. |
deletion_cost |
Optional. Specify the cost of deleting a character. Default is 1. |
Return Value
Returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.
Example:
The example below shows the usage of levenshtein() function.
<?php $str1 = "Hello World"; $str2 = "Hello Marry"; echo "Levenshtein distance: " .levenshtein($str1, $str2)."\n"; echo "Levenshtein distance: " .levenshtein($str1, $str2, 2, 2, 1)."\n"; ?>
The output of the above code will be:
Levenshtein distance: 4 Levenshtein distance: 8
❮ PHP String Reference