Home  >  Article  >  Backend Development  >  How to use php levenshtein function

How to use php levenshtein function

青灯夜游
青灯夜游Original
2019-05-25 16:36:272955browse

The levenshtein() function is a built-in function in PHP used to calculate the Levenshtein distance between two strings. Levenshtein distance, also known as edit distance, refers to the minimum number of editing operations (replacement, insertion, deletion of a character) required between two strings to convert one string into another.

How to use php levenshtein function

php How to use the levenshtein() function?

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 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.

Syntax:

levenshtein(string1,string2,insert,replace,delete)

Parameters: The levenshtein() function accepts two required parameters and 3 optional parameters.

● 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.

Return value: Returns the Levenshtein distance between the two parameter strings. If one of the strings exceeds 255 characters, it returns -1.

Let’s take a look at how to use the php levenshtein() function through an example.

Example 1

<?php
$data = "hello";
$res = "world";
echo levenshtein($data,$res);
?>

Output:

4

Example 2:

<?php
$str1 = "Learning PHP";
$str2 = "is a good choise";
echo levenshtein($str1,$str2);
?>

Output:

14

The above is the detailed content of How to use php levenshtein function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn