I'm making a feature like stated in the title that gives suggestions based on what terms exist in the database;
I have a working example below that works for one term. such as "oranges", or "yellow bananas".
However, I need it to work for multiple terms so if my database contains the words "grapes", "blue", and "today", and the user types in "graps, bleu, todya" it will run through each word inputed by the user, to each word in the database, and find a suggestion for each word, then display them all. so the suggestions would look like this: "grapes, blue, today", when the user inputs: "graps, bleu, todya".
here is my current code that works for one term:
$input = $_POST['input']; // will be a list of comma seperated terms from the user(only works with one term now);
$words = "yellow,green,grapes,blue,court"; // for simplicity, real terms in database
$words = explode(',', $words); // words is now an array
$shortest = -1;
foreach ($words as $word)
{
$lev = levenshtein($input, $word);
if ($lev == 0)
{
$closest = $word;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0)
{
$closest = $word;
$shortest = $lev;
}
}
echo $closest; // the result(suggestion);
}
This code works perfectly until the user types in a comma, then another word...
I've tried exploding the input by it's commas then adding another foreach statement like the code below, but it isn't working...
$input = $_POST['input'];
$input = explode(',', $input);
$words = "yellow,green,grapes,blue,court";
$words = explode(',', $words);
$shortest = -1;
foreach($input as $compare)
{
foreach ($words as $word)
{
$lev = levenshtein($compare, $word);
if ($lev == 0)
{
$closest = $word;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0)
{
$closest = $word;
$shortest = $lev;
}
}
echo $closest . ", ";
}
I've tried many variations of this as well and I really can't understand why it isn't working... :(
any suggestions?