PHP levenshtein() Function

Definition

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

The Levenshtein distance is the number of characters to replace, insert or delete to transform string1 into string2.

By default, PHP gives replace, insert, and delete equal weight. We can define the cost of each operation by setting the optional insert, replace, and delete parameters.

Syntax

PHP levenshtein() Function has the following syntax.

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

Parameter

ParameterIs RequiredDescription
string1Required.First string to compare
string2Required.Second string to compare
insertOptional.The cost of inserting a character. Default is 1
replaceOptional.The cost of replacing a character. Default is 1
deleteOptional.The cost of deleting a character. Default is 1

Return

PHP levenshtein() function Returns the Levenshtein distance between the two argument strings or -1, if one of the strings exceeds 255 characters.

Example

Calculate the Levenshtein distance between two strings:


<?php//ww  w  .  j ava 2 s .c  o  m
echo levenshtein("Hello World","ello World from java2s.com");
echo "\n";
echo levenshtein("Hello World","ello World from java2s.com",10,20,30);
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions