How to calculate Levenshtein distance between two strings (min chars to transform str1 into str2) in PHP

1 Answer

0 votes
/*
The Levenshtein distance = the minimal number of characters you have to 
replace, insert or delete to transform string1 into string2. 
*/

// Function to find the closest word from an array
function findClosestWord(string $input, array $words): string {
    $shortest_dis = -1;
    $closest_w = '';

    foreach ($words as $word) {
        // calculate the distance between $input and $word
        $dis = levenshtein($input, $word);

        // exact match?
        if ($dis == 0) {
            $closest_w = $word;
            $shortest_dis = 0;
            break;
        }

        // check if this is the closest match so far
        if ($dis <= $shortest_dis || $shortest_dis < 0) {
            $closest_w = $word;
            $shortest_dis = $dis;
        }
    }

    return $closest_w;
}

$s = 'PHHP';
$arr = array('C', 'PHP', 'C++', 'Java', 'C#', 'JavaScript');

$closest_w = findClosestWord($s, $arr);

echo "word: $s\n";
if ($closest_w === $s) {
    echo "Exact match found: $closest_w";
} else {
    echo "Did you mean: $closest_w?";
}


 
/*
run: 
 
word: PHHP
Did you mean: PHP?

*/
 

 



answered Jul 3, 2016 by avibootz
edited Dec 18, 2025 by avibootz
...