基本上我有很多可能性,例如运动队或运动名称:
多伦多枫叶队 新泽西魔鬼 波士顿红袜子 曲棍球 足球 等...
所以我有一个搜索栏,用户可以在其中键入他们想要的任何内容。我需要一种方法来获取他们输入的内容,将它与数组进行比较,如果匹配得足够紧,则将其添加到过滤器变量中。
示例:
if (strpos($userSearch, 'Hockey') !== false) {
$pageVar = $pageVar . "+" . "Hockey";
}
这样做^有一些挫折可以说有人进入hockie或类似的东西..或多伦多而不是多伦多枫叶......没有经历所有可能的情况一个接一个必须有一个更好的方法。 。
由于
答案 0 :(得分:1)
对于完全匹配,您可以使用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\n";
}
对于类似匹配,您可以尝试levenshtein()
(php doc页面上的第一个示例)
$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\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
结果:
Input word: carrrot
Did you mean: carrot?
对于类似匹配,您可以尝试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\n";
if ($shortest == 100) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
结果:
Input word: iApple
Did you mean: apple?
要获得良好的效果,您可以结合使用 levenshtein()
, similar_text()
和 soundex()
强>