我想在用户搜索错误字词时显示您的意思是替代方案。此代码有效,但某些结果无关紧要。示例:我的表中有 apple 记录。如果用户搜索 apple1 结果为:您的意思是 apple?,但是如果用户搜索 aple 结果是:您的意思是多尔?有没有办法显示更相关的结果?这是一个代码:
$search = $_GET ['search'];
$results = array();
foreach ($db->query("SELECT id FROM table") as $name) {
$results[] = $name['id'];
}
$shortest = -1;
foreach ($results as $word) {
$lev = levenshtein($search, $word);
if ($lev <= $shortest || $shortest < 0) {
$closest = $word;
$shortest = $lev;
}
}
echo $closest;