How can the Levenshtein distance algorithm be utilized in PHP to detect and suggest corrections for spelling errors in text input?

The Levenshtein distance algorithm can be utilized in PHP to detect and suggest corrections for spelling errors in text input by calculating the minimum number of single-character edits (insertions, deletions, or substitutions) needed to transform one word into another. By comparing the input word with a dictionary of valid words, suggestions for corrections can be generated based on words with the smallest Levenshtein distance to the input word.

function suggestCorrection($inputWord, $dictionary) {
    $minDistance = PHP_INT_MAX;
    $suggestion = '';

    foreach ($dictionary as $word) {
        $distance = levenshtein($inputWord, $word);
        if ($distance < $minDistance) {
            $minDistance = $distance;
            $suggestion = $word;
        }
    }

    return $suggestion;
}

$inputWord = 'aple';
$dictionary = ['apple', 'banana', 'orange', 'pear'];

$suggestedCorrection = suggestCorrection($inputWord, $dictionary);
echo "Did you mean: $suggestedCorrection?";