PHP levenshtein() function

Example

Calculate the Levenshtein distance between two strings:

<?php
echo levenshtein("Hello World","ello World");
echo "<br>";
echo levenshtein("Hello World","ello World",10,20,30);
?>

Run Examples

Definition and Usage

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

Levenshtein distance, also known as edit distance, refers to the minimum number of editing operations required to transform one string into another. Permitted editing operations include replacing one character with another, inserting a character, and deleting a character.

By default, PHP gives each operation (replacement, insertion, and deletion) the same weight. However, you can define the cost of each operation by setting the optional insert, replace, and delete parameters.

Note:The levenshtein() function is case-insensitive.

Note:The levenshtein() function is faster than similar_text() The function is faster. However, the similar_text() function can provide you with a more accurate result through fewer required modifications.

Syntax

levenshtein(string1,string2,insert,replace,delete)
Parameters Description
string1 Required. The first string to compare.
string2 Required. The second string to compare.
insert Optional. The cost of inserting a character. The default is 1.
replace Optional. The cost of replacing a character. The default is 1.
delete Optional. The cost of deleting a character. The default is 1.

Technical Details

Return Value: Returns the Levenshtein distance between two strings. If one of the strings exceeds 255 characters, it returns -1.
PHP Version: 4.0.1+