English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP levenshtein() Function Usage and Example

PHP String String Function Manual

The levenshtein() function is used to calculate the editing distance between two strings.

Syntax

int levenshtein ( string $str1 , string $str2 )

Definition and Usage

Used to calculate the editing distance between two strings.

The editing distance refers to the two strings, through replacement, insertion, deletion, and other operations to convert the string str1Convert to str2The minimum number of characters required for the operation. The complexity of the algorithm is O(m*n), where n and m are the lengths of str1 and str2The length (when and the algorithm complexity is O(max(n,m)**3)'s similar_text() compared, this function is still quite good, although it is still time-consuming.()).
In the simplest form, the function only takes two strings as parameters and calculates the number of operations required to convert str1Convert to str2The number of operations required.
The second variant will use three additional parameters to define the number of insertion, replacement, and deletion operations. This variant is more general and adaptable, but less efficient.

Return Value

It returns the Levenshtein distance between the two parameter strings, otherwise returns-1

Parameter

Serial NumberParameters and Description
1

str1

One of the strings in the editing distance

2

str2

The other string in the editing distance

3

cost_ins

Define the number of insertion operations

4

cost_del

Define the number of replacement operations

Online Example

Try the following example to calculate the Levenshtein distance between two strings:

<?php
   //Calculate the editing distance between two strings
   echo 'the distance between two strings is ';
   echo levenshtein("Hello World","ello World");
?>
Test and see‹/›

Output Result-

the distance between two strings is 1

PHP String String Function Manual