PHP levenshtein()Functions

PHP String 参考手册PHP String Reference Manual

Examples

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 Example »

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 edit operations required to transform one string into another between two strings. Permitted 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, similar_text() 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 one of the strings exceeds 255 characters.
PHP Version: 4.0.1+


PHP String 参考手册PHP String Reference Manual Other Extensions