Levenshtein: MySQL + PHP

user317005 picture user317005 · Jan 12, 2011 · Viewed 35.7k times · Source
$word = strtolower($_GET['term']); 

$lev = 0;

$q = mysql_query("SELECT `term` FROM `words`"); 
while($r = mysql_fetch_assoc($q)) 
{ 
    $r['term'] = strtolower($r['term']); 

    $lev = levenshtein($word, $r['term']);

    if($lev >= 0 && $lev < 5)
    {
        $word = $r['term'];
    }
}

How can I move all that into just one query? Don't want to have to query through all terms and do the filtering in PHP.

Answer

rik picture rik · Jan 12, 2011

You need a levenshtein function in MySQL and query like

$word = mysql_real_escape_string($word);
mysql_qery("SELECT `term` FROM `words` WHERE levenshtein('$word', `term`) BETWEEN 0 AND 4");