我刚刚用一小部分测试条目尝试了你的代码,它运行良好。也许您从查询中得到奇怪的结果?这是代码:
$my_word = $_REQUEST['value'];
$bestMatch = array('word' => $my_word, 'match' => 2);
$result = array("exam", "clinicals", "templates", "reschedule", "crafting", "php", "answer");
$storeArray = Array();
foreach ($result as $keyword) {
similar_text($keyword, $my_word, $percent);
if ($percent > $bestMatch['match'])
$bestMatch = array('word' => $keyword, 'match' => $percent);
}
if ($bestMatch['match'] < 70)
echo 'Did you mean: <strong>'.$bestMatch['word'].'</strong> p:'.$bestMatch['match'];
无论如何similar_text()
,这可能不是正确的功能,因为它通常会在短字符串/单词上产生误导性结果。
正如已经指出的那样,您应该将levenshtein()
其用于此类任务。它计算必须进行多少更改才能匹配单词,其中删除、添加和更改字符是一种更改。您可以(并且在这种情况下应该)修改更改为 2 的成本,以使用短字符串获得更好的结果。
levenshtein 函数在性能方面的成本低于similar_text,但它不会以百分比返回结果!
levenshtein方法的代码:
$my_word = $_REQUEST['value'];
$bestMatch = array('word' => $my_word, 'match' => 2);
$result = array("exam", "clinicals", "templates", "reschedule", "crafting", "php", "answer");
$storeArray = Array();
foreach ($result as $keyword) {
$lev = levenshtein ($keyword, $my_word, 1, 2, 1);
if (!isset($lowest) || $lev < $lowest) {
$bestMatch = array('word' => $keyword, 'match' => $lev);
$lowest = $lev;
}
}
if ($bestMatch['match'] > 0)
echo 'Did you mean: <strong>'.$bestMatch['word'].'</strong> l:'.$bestMatch['match'];