I have a basic search script which I'm working on. I want users to be able to enter several keywords. If one of these keywords are mis-spelt, I want to change that word for the search results and/or display a "did you mean ..." message.
I have tried levenshtein but it only seems to work for a single word and doesn't seem very reliable anyway. When using this function, in testing, I came up with this:
<?php
$input = 'ornage ptoato';
$possible_words = explode(' ', trim(strtolower($input)));
foreach($possible_words as $value){
$words = array('sony','red', 'indigo','orange','bell','toshiba','potato');
$shortest = -1;
foreach ($words as $word) {
$lev = levenshtein($value, $word);
if ($lev == 0) {
$closest = $word;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
}
echo "Input word: $input<br>";
if ($shortest == 0) {
echo "Exact match found: $closest";
} else {
echo "Did you mean: $closest?\n";
}
?>
There is foreach within a foreach because I was trying to do it for each word within the search string.
I basically want it to work like Google's "did you mean.." and eBay's "0 results found for one two theer, so we searched for one two three".