designbycode / levenshtein-distance
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.
Fund package maintenance!
designbycode
Requires
- php: ^8.1|^8.2|^8.3
Requires (Dev)
- laravel/pint: ^1.0
- pestphp/pest: ^2.20
- spatie/ray: ^1.28
This package is auto-updated.
Last update: 2024-12-07 23:04:23 UTC
README
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.
Installation
You can install the package via composer:
composer require designbycode/levenshtein-distance
Method: calculate
Parameters
- mixed $str1: The first string.
- mixed $str2: The second string.
Return Value
- int: The Levenshtein distance between the two strings.
Description
- Calculates the Levenshtein distance between two strings. The method throws a TypeError if either of the input parameters is not a string.
Use Cases
- 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.
Usage
Example 1: Calculating the Levenshtein distance between two strings
$str1 = 'kitten'; $str2 = 'sitting'; $distance = LevenshteinDistance::calculate($str1, $str2); echo "Levenshtein distance: $distance"; // Output: 3
Example 2: Handling non-string input
$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 }
Example 3: Using Levenshtein distance for spell checking
$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
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.