Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP levenshtein() Function

PHP levenshtein() Function

PHP String Reference Manual PHP String Reference Manual

Example

Calculate the Levenshtein distance between two strings:

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

Run Example »


Definition and Usage

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

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

By default, PHP assigns the same weight to each operation (replace, insert, and delete). 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 the similar_text() function. However, the similar_text() function provides more accurate results with 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. Default is 1.
replace Optional. The cost of replacing a character. Default is 1.
delete Optional. The cost of deleting a character. Default is 1.

Technical Details

Return Value: Returns the Levenshtein distance between the two argument strings, or -1 if either string is longer than 255 characters.
PHP Version: 4.0.1+

PHP String Reference Manual PHP String Reference Manual