PHP levenshtein() Function (original) (raw)

Last Updated : 21 Jun, 2023

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 string1totransformittoastringstring1 to transform it to a string string1totransformittoastringstring2.
Syntax:

int levenshtein($str1, $str2)

Example:

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

Input: str1=′ComputerSciencePortal′,str1 = 'Computer Science Portal', str1=ComputerSciencePortal,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 `

str1andstr1 and str1andstr2 $str1 = 'abc'; $str2 = 'aef'; print_r(levenshtein($str1, $str2)); ?>

`

Output:

2

Program 2:

PHP `

str1andstr1 and str1andstr2 $str1 = 'Hello World'; $str2 = 'Hello d'; print_r(levenshtein($str1, $str2)); ?>

`

Output:

4

Program 3:

php `

str1andstr1 and str1andstr2 $str1 = 'Computer Science Portal'; $str2 = 'Computer Portal'; print_r(levenshtein($str1, $str2)); ?>

`

Output:

8

Reference:
https://www.php.net/manual/en/function.levenshtein.php