HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

levenshtein

Description

The levenshtein of String for PHP calculates Levenshtein distance between two strings.

The Levenshtein distance is defined as the minimal number of characters you have to insert, replace, or delete to transform string1 into string2.

If insertion_cost, replacement_cost and/or deletion_cost are unequal to 1, the algorithm adapts to choose the cheapest transforms.

Syntax

levenshtein(
    string $string1,
    string $string2,
    int $insertion_cost = 1,
    int $replacement_cost = 1,
    int $deletion_cost = 1
): int

Parameters

string1

One of the strings being evaluated for Levenshtein distance.

string2

One of the strings being evaluated for Levenshtein distance.

insertion_cost

Defines the cost of insertion.

replacement_cost

Defines the cost of replacement.

deletion_cost

Defines the cost of deletion.

Return

Returns the Levenshtein distance between the two argument strings.

Examples

1 · string1 string2 · same

<?

$string1 = "string";
$string2 = "string";

$return = levenshtein($string1, $string2);

echo $return;
0

2 · string1 string2 · different

<?

$string1 = "";
$string2 = "string";

$return = levenshtein($string1, $string2);

echo $return;
6

3 · insertion_cost

<?

$string1 = "ring";
$string2 = "string";
$insertion_cost = 10;

$return = levenshtein($string1, $string2, $insertion_cost);

echo $return;
20

4 · replacement_cost

<?

$string1 = "strong";
$string2 = "string";
$insertion_cost = 100;
$replacement_cost = 10;

$return = levenshtein($string1, $string2, $insertion_cost, $replacement_cost);

echo $return;
10

5 · deletion_cost

<?

$string1 = "stringent";
$string2 = "string";
$insertion_cost = 1000;
$replacement_cost = 100;
$deletion_cost = 10;

$return = levenshtein($string1, $string2, $insertion_cost, $replacement_cost, $deletion_cost);

echo $return;
30

6 · single

<?

$string1 = "caret";

$array =
[
    "apple",
    "pineapple",
    "banana",
    "orange",
    "radish",
    "carrot",
    "pea",
    "bean",
    "tomato",
    "potato"
];

$num = -1;

foreach($array as $string2)
{
    $return = levenshtein($string1, $string2);

    if($return == 0)
    {
        $num = $return;
        $word = $string2;

        break;
    }

    if(($return <= $num) || ($num == -1))
    {
        $num = $return;
        $word = $string2;
    }
}

echo "$string1: $word: $num";
caret: carrot: 2

7 · multiple

<?

$string1 = "caret";

$array1 = [];
$array2 =
[
    "apple",
    "pineapple",
    "banana",
    "orange",
    "radish",
    "carrot",
    "pea",
    "bean",
    "tomato",
    "potato"
];

foreach($array2 as $string2)
{
    $return = levenshtein($string1, $string2);

    $array1[$string2] = $return;
}

asort($array1);

print_r($array1);
Array
(
    [carrot] => 2
    [pea] => 4
    [apple] => 5
    [banana] => 5
    [orange] => 5
    [radish] => 5
    [bean] => 5
    [tomato] => 5
    [potato] => 5
    [pineapple] => 8
)