The LevenshteinDistance class provides a method to calculate the Levenshtein distance between two strings. The Levenshtein distance is a measure of the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other.
You can install the package via composer:
composer require designbycode/levenshtein-distance
- mixed $str1: The first string.
- mixed $str2: The second string.
- int: The Levenshtein distance between the two strings.
- Calculates the Levenshtein distance between two strings. The method throws a TypeError if either of the input parameters is not a string.
- Spell Checking: Calculate the Levenshtein distance between a user's input and a list of known words to suggest corrections.
- Text Similarity: Measure the similarity between two pieces of text by calculating the Levenshtein distance.
- Data Validation: Verify the correctness of user input by calculating the Levenshtein distance between the input and a known valid value.
$str1 = 'kitten';
$str2 = 'sitting';
$distance = LevenshteinDistance::calculate($str1, $str2);
echo "Levenshtein distance: $distance"; // Output: 3
$str1 = 'hello';
$nonString = 123;
try {
LevenshteinDistance::calculate($str1, $nonString);
} catch (TypeError $e) {
echo "Error: " . $e->getMessage(); // Output: Argument 2 passed to LevenshteinDistance::calculate() must be of the type string
}
$userInput = 'teh';
$knownWords = ['the', 'tea', 'ten'];
$minDistance = PHP_INT_MAX;
$closestWord = '';
foreach ($knownWords as $word) {
$distance = LevenshteinDistance::calculate($userInput, $word);
if ($distance < $minDistance) {
$minDistance = $distance;
$closestWord = $word;
}
}
echo "Did you mean: $closestWord"; // Output: Did you mean: the
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.