Skip to content
Related Articles

Related Articles

PHP | levenshtein() Function

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 16 Jul, 2021

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

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: 
 

PHP




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


Output: 
 

2

Program 2: 
 

PHP




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


Output: 
 

4

Program 3: 
 

php




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


Output: 
 

8

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!