PHP Tutorial - PHP levenshtein() Function


The levenshtein() function returns the Levenshtein distance between two strings case-insensitive.

The Levenshtein distance is the number of characters to replace, insert or delete to transform string1 into string2.

By default, PHP gives replace, insert, and delete equal weight. We can define the cost of each operation by setting the optional insert, replace, and delete parameters.


PHP levenshtein() Function has the following syntax.



ParameterIs RequiredDescription
string1Required.First string to compare
string2Required.Second string to compare
insertOptional.The cost of inserting a character. Default is 1
replaceOptional.The cost of replacing a character. Default is 1
deleteOptional.The cost of deleting a character. Default is 1


PHP levenshtein() function Returns the Levenshtein distance between the two argument strings or -1, if one of the strings exceeds 255 characters.


Calculate the Levenshtein distance between two strings:

echo levenshtein("Hello World","ello World from");
echo "\n";
echo levenshtein("Hello World","ello World from",10,20,30);

The code above generates the following result.