1

我有以下代码,当我搜索一个词时,它会告诉我你的意思。问题是如果我输入“clin”我希望它返回临床但它返回“重新安排”

$my_word = $_POST['value'];
$bestMatch = array('word' = > $my_word, 'match' = > 2);
$result = mysql_query("SELECT keyword FROM athena");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    similar_text($row['keyword'], $my_word, $percent);
    if ($percent > $bestMatch['match'])
       $bestMatch = array('word' = > $row['keyword'], 'match' = > $percent);
}
if ($bestMatch['match'] < 70)
   echo 'Did you mean: <strong>'.$bestMatch['word'].'</strong>';
4

2 回答 2

0

我不熟悉similar_word()PHP,但您也可以尝试以下方法:

http://www.php.net/manual/en/function.levenshtein.php 这是一种流行的算法,用于执行您想要的搜索类型。

于 2012-07-04T02:05:08.340 回答
0

我刚刚用一小部分测试条目尝试了你的代码,它运行良好。也许您从查询中得到奇怪的结果?这是代码:

$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'];
于 2012-07-04T02:38:46.010 回答