using levenstein function in querying to a database

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
icesha
Forum Newbie
Posts: 11
Joined: Tue May 01, 2007 3:15 am

using levenstein function in querying to a database

Post 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";
}
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post 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.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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.
Post Reply