PHP | levenshtein() Function


The levenshtein() function is an inbuilt function in PHP. The levenshtein() function is used to calculate the levenshtein distance between two strings. The Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string $string1 to transform it to a string $string2.

Syntax:

int levenshtein($str1, $str2)

Example:



Input: $str1 = 'GeeksforGeeks', $str2 = 'Geeksfor'
Output: 5

Input: $str1 = 'Computer Science Portal', $str2 = 'Computer Portal'
Output: 8

Parameters: The levenshtein() function accepts two parameters, both of the parameters are compulsory:

  1. $str1: This is a required parameter which specifies the string to be transformed to another.
  2. $str2: This is also a required parameter which specifies the string in which the first string($str1) needed to be trasformed.

Return Value: The levenshtein() function returns an integral value which is the levenshtein distance otherwise -1, if one of the arguments exceeds the limit of 255 characters.

Below programs illustrate The levenshtein() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
    // PHP code to find levenshtein distance
    // between $str1 and $str2
    $str1 = 'abc';
    $str2 = 'aef';
      
    print_r(levenshtein($str1, $str2));
?>

chevron_right


Output:

2

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
    // PHP code to find levenshtein distance
    // between $str1 and $str2
    $str1 = 'Hello World';
    $str2 = 'Hello d';
      
    print_r(levenshtein($str1, $str2));
?>

chevron_right


Output:

4

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
    // PHP code to find levenshtein distance
    // between $str1 and $str2
    $str1 = 'Computer Science Portal';
    $str2 = 'Computer Portal';
      
    print_r(levenshtein($str1, $str2));
?>

chevron_right


Output:

8

Reference:
http://php.net/manual/en/function.levenshtein.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.