For an exact match, you can use in_array()
$input = 'carrrot';
$words = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');
if (in_array($words, $input)) {
echo "$input was found in array
";
}
For similar match, you can try levenshtein()
(first example on php doc page)
$input = 'carrrot';
$words = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');
$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 "Input word: $input
";
if ($shortest == 0) {
echo "Exact match found: $closest
";
} else {
echo "Did you mean: $closest?
";
}
Result:
Input word: carrrot
Did you mean: carrot?
also for similar match, you can try similar_text()
$input = 'iApple';
$words = array('apple','pineapple','banana','orange','radish','carrot','pea','bean','potato');
$shortest = 70;
foreach ($words as $word) {
similar_text($word, $input, $percent);
$percent = round($percent);
if ($percent == 100) {
$closest = $word;
$shortest = 100;
break;
}
if ($percent >= $shortest) {
$closest = $word;
$shortest = $percent;
}
}
echo "Input word: $input
";
if ($shortest == 100) {
echo "Exact match found: $closest
";
} else {
echo "Did you mean: $closest?
";
}
Result:
Input word: iApple
Did you mean: apple?
To achieve good results you can use a combination of levenshtein()
, similar_text()
, and soundex()