PHP字符串搜索从大数组页面过滤器


php string search from large array for page filter

基本上我有一个巨大的数组的可能性,例如可以是运动队或运动名称:

多伦多枫叶新泽西魔鬼波士顿红袜曲棍球足球等等…

所以我有一个搜索栏,用户可以输入任何他们想要的。我需要一种方法来获取他们输入的内容,将其与数组进行比较,如果它足够接近匹配,则将其添加到过滤器变量中。

的例子:

if (strpos($userSearch, 'Hockey') !== false) {
    $pageVar = $pageVar . "+" . "Hockey";
}

这样做^有一些挫折,比如有人输入曲棍球或类似的东西…或者多伦多而不是多伦多枫叶…不必一一考虑所有可能的情况,一定有更好的办法。

谢谢

对于精确匹配,您可以使用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文档页面的第一个例子)

$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()