Page 1 of 1

using levenstein function in querying to a database

Posted: Sun Sep 09, 2007 8:43 pm
by icesha
How can i implement the levenstein function in php in querying in my database.

please help. here's is a sample. how can i apply this is querying in database.

Code: Select all

// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

Posted: Sun Sep 09, 2007 11:14 pm
by Zoxive
How about an example of your current code you are using instead of the example on php.net?

We are here to help, not work for you.

Posted: Mon Sep 10, 2007 2:53 am
by Kieran Huggins
This question has been asked before:

What you probably want is the levenshtein (there is an H in there!) of the soundex of each term - it will give you a much better fuzzy search. MySQL does it WAAAAYYYY faster than PHP, so convert them in the DB query instead of PHP.

For more, check out my earlier post:
viewtopic.php?p=349907#349907

and the search for "soundex" in general.