类似文本 php mysql


Similar Text php mysql

我有以下代码,当我搜索一个单词时,它会显示一个你的意思。 问题是,如果我输入"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>';

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

$my_word = $_REQUEST['value'];
$bestMatch = array('word' => $my_word, 'match' => 2);
$result = array("exam", "clinicals", "templates", "reschedule", "crafting", "php", "answerswer");
$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", "answerswer");
$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'];

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

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