PHP code example of designbycode / levenshtein-distance

1. Go to this page and download the library: Download designbycode/levenshtein-distance library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

designbycode / levenshtein-distance example snippets


$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