Home >Backend Development >PHP Tutorial >PHP function levenshtein() that returns the distance between two strings
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); ?>
Definition and usage
levenshtein() function returns the Levenshtein distance between two strings distance.
Levenshtein distance, also known as edit distance, refers to the minimum number of edit operations required between two strings to convert one string into another. Permitted editing operations include replacing one character with another, inserting a character, and deleting a character.
By default, PHP gives equal weight to every operation (replacement, insertion, and deletion). However, you can define the cost of each operation by setting the optional insert, replace, and delete parameters.
Note: The levenshtein() function is not case-sensitive.
Note: levenshtein() function is faster than similar_text() function. However, the similar_text() function provides more accurate results with fewer modifications required.
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 the two parameter strings, or -1 if one of the strings exceeds 255 characters. PHP version: 4.0.1+ If one of the strings exceeds 255 characters, levenshtein() The function returns -1.levenshtein() function is not case sensitive.
levenshtein() function is faster than similar_text() function. However, the similar_text() function provides more accurate results that require fewer modifications.
Example
<?php echo levenshtein("Hello World","ello World"); echo "<br />"; echo levenshtein("Hello World","ello World",10,20,30); ?>Output:
1 30
The above is the detailed content of PHP function levenshtein() that returns the distance between two strings. For more information, please follow other related articles on the PHP Chinese website!