The levenshtein Function

The levenshtein function takes two strings and returns a number - the Levenshtein distance between them. The smaller this number, the more similar the strings are. The first parameter is the first string, the second parameter is the second string. Additional parameters can also be specified to configure the cost of operations.

Syntax

phplevenshtein(string1, string2, [cost_ins], [cost_rep], [cost_del]);

Example

Let's compare two similar strings:

php<?php
  echo levenshtein('kitten', 'sitting');
?>

The result of executing the code:

php3

Example

Let's compare two completely different strings:

php<?php
  echo levenshtein('hello', 'world');
?>

The result of executing the code:

php4

Example

Using custom operation costs:

php<?php
  echo levenshtein('test', 'text', 1, 2, 1);
?>

The result of executing the code:

php2

See Also

  • the similar_text function,
    which calculates the similarity degree of two strings
  • the soundex function,
    which calculates the soundex key of a string