EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP levenshtein()

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP levenshtein()

PHP levenshtein()

Introduction of PHP levenshtein()

The levenshtein() is an inbuilt function in PHP which is used to determine a unit of distance called Levenshtein distance in comparison with two strings. The definition of Levenshtein distance stands for the total number of characters which are to be modified like replacing, inserting or deleting the input string to transform it into another string.

There is equal weightage given to all the above 3 modifications (replace, delete, insert) by default in PHP. But there is an option for us to input the cost or the weightage of each of these operations by giving the optional parameters for the above. The algorithm used for this function has a complexity of O(a*b) where a and b are the length of strings str1 and str2 respectively.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

There are a few things to note of this function though:

  • This levenshtein() function is case insensitive one.
  • There is a similar function to levenshtein which is called the similar_text() function. As compared to that, levenshtein() function is a to faster but simiar_text() function returns a more accurate results with a limited number of changes needed. Also, levenshtein() is more expensive.

Syntax and Parameters

Here we discuss the syntax and parameters:

Syntax:

levenshtein(str1,str2,insert,replace,delete)

Parameters:

  • str1: Mandatory input parameter required and is the first string to be compared with.
  • str2: This is the second string to be compared with and is also a mandatory parameter.
  • insert: An optional parameter and represents the cost at which a character will be inserted.
  • replace: Also an optional one which represents the cost at which a character will be replaced.
  • delete: Another optional parameter representing the cost at which a character will be deleted.

The default value for all the last 3 parameters is 1.

Return Value: This function outputs the Levenshtein distance between the two input strings. It returns the value -1 if even any one of the total string characters crosses 255.

Examples of PHP levenshtein()

Let us take a few examples to understand the working of levenshtein function.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,731 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #1

Code:

<?php
// PHP code to determine levenshtein distance
// between 2 strings $s1 and $s2
$s1 = 'rdo';
$s2 = 'rst';
print_r(levenshtein($s1, $s2));
?>

Output:

PHP levenshtein()-1.1

This is a basic example where the 2 input strings s1 and s2 have one word each consisting of 3 different letters. Now the levenshtein function compares these 2 strings character by character and finds out the difference in the number of characters. Here there are 2 letters which are not in common out of the 3. So to make the first string the same as the second string we need to add the 2 letters “s,t” to it hence the output 2.

Example #2

Code:

<?php
// PHP code to determine levenshtein distance
// between 2 strings $s1 and $s2
$s1 = 'first string';
$s2 = 'second string';
print_r(levenshtein($s1, $s2));
?>

Output:

PHP levenshtein()-1.2

In this basic example, we can find out the levenshtein distance between the 2 input strings which are represented by s1 and s2 here. If we compare the characters of the two strings, we can see that they have one word in common I.e. “string”. And in the remaining words, it compares between “first” and “second” words and also with the common word “string”. Here the only letters not in common are “f,e,c,o,d” and the extra “s”. So levenshtein function returns the output as 6 meaning these 6 letters are the difference between these 2 input strings and using which these 2 strings can be made equal in terms of characters.

Example #3

Code:

<?php
// PHP code to determine levenshtein distance
// between $s1 and $s2
$s1 = 'Common Three Words';
$s2 = 'Common Words';
echo("The Levenshtein distance is: ");
print_r(levenshtein($s1, $s2));
?>

Output:

Output -1.3

Here in this example, we can see that the first string has 3 words whereas the second string has only 2 words. And we can notice that both of these 2 words in the second string are already present in the first string. Hence the only difference in characters here will be the word “Three” which 5 characters. An interesting thing to notice here that the output gives 6 which means that even the extra space is also considered as a character.

Example #4

<?php
// Giving a misspelled word as input
$ip = 'giraffee';
// sample set array to compare with
$word_list = array('cat','dog','cow','elephant',
'giraffe','eagle','pigeon','parrot','rabbit');
// Since shortest distance is not found yet
$short = -1;
// Looping through array to find the closest word
foreach ($word_list as $word_list) {
// Calculating the levenshtein distance between
// input word and the current word
$levn = levenshtein($ip, $word_list);
// To check for the matching word
if ($levn == 0) {
// This is the closest one which is an perfect match
$closest = $word_list;
$short = 0;
// Here we break from foreach loop
// when the exact match is found
break;
}
// When the distance shown here is less than shortest distance
// found in next iteration or if the next shortest word is
// yet to be found
if ($levn <= $short || $short < 0) {
// Setting the shortest distance and one having
// closest match to the input word
$close = $word_list;
$short = $levn;
}
}
echo "Input word: $ip\n";
if ($short == 0) {
echo "The closest/exact match found to the input word is: $close\n";
} else {
echo "Did you mean to spell: $close?\n";
}
?>

Output:

Output-1.4

The above example shows us one of the different cases where this levenshtein function can be implemented. Here we are helping the user to correct a misspelled word by comparing it with a pre-defined set of an array which has the list of correct words.

So at first, we are accepting an input word from the user which is typically misspelt (giraffee). We are defining an array set of correct animal names as shown which also has the correct spelling for input word (giraffe). A foreach loop is used to iterate through the array list and find the closest word which is matching with the input and this is done with the help of levenshtein function. The loop breaks when an exact match or the closest one is found. At the end, we compare the distance with the short parameter and if the distance is 0 it means that an exact match is found for the input word which is then printed in the output.

Conclusion

So basically levenshtein function returns the distance in integer values returned by comparing the character by character of the 2 input strings given to it. The first two parameters are the input strings which are mandatory and the last 3 parameters are optional which represent the cost of delete, insert or replace operations.

Recommended Articles

This is a guide to PHP levenshtein(). Here we also discuss the Introduction and syntax and parameters of php levenshtein() along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. PHP Pagination
  2. PHP header()
  3. PHP parse_str()
  4. PHP wordwrap()
  5. PHP strtok()

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More