Hướng dẫn dùng levenshtien distance trong PHP

  • Trang chủ
  • Phát triển web
  • PHP
  • Hàm levenshtein() trong PHP

Hướng dẫn cách sử dụng hàm levenshtein() trong lập trình PHP

Tác dụng của hàm levenshtein()

The levenshtein() function calculates Levenshtein distance between two strings.

The following table summarizes the technical details of this function.

Return Value:Returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.
Version:PHP 4.0.1+


Syntax

The basic syntax of the levenshtein() function is given with:

levenshtein(string1, string2, cost_insert, cost_replacement, cost_delete);

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform string1 into string2.

The following example shows the levenshtein() function in action.

Example

";
echo levenshtein("weight", "wait")."
"; echo levenshtein("hour", "our"); ?>

Tip: The levenshtein() function is faster than the similar_text() function. However, similar_text() provides better results with less modifications.

Note: The Levenshtein distance is defined as the minimum number of characters you have to replace, insert or delete to transform string1 into string2. The complexity of the algorithm is O(m*n), where n and m are the length of string1 and string2.


Parameters

The levenshtein() function accepts the following parameters.

ParameterDescription
string1 Required. Specifies the first string being evaluated for Levenshtein distance.
string2 Required. Specifies the second string being evaluated for Levenshtein distance.
cost_insert Optional. Defines the cost of insertion.
cost_replacement Optional. Defines the cost of replacement.
cost_delete Optional. Defines the cost of deletion.


More Examples

Here're some more examples showing how levenshtein() function actually works:

The following example demonstrates how to search for the closest match of a misspelled word inside an array of words. You can adjust the sensitivity of the result according to your need.

Example

";

// Specify the sensitivity of the result
if($shortest > 3){
    echo "No appropriate match found." . "
"; } elseif($shortest == 0){ echo "Exact match found: $closest" . "
"; } else{ echo "Did you mean: $closest?"; } ?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới