php - 查找拼写最接近的单词

标签 php mysql arrays autocomplete autocorrect

我正在尝试在我的网络应用程序中实现搜索功能,我想做的是在数据库中搜索一个单词,如果它不存在,系统应该告诉我或找到与该单词最接近的匹配项。我实现了在数据库中搜索并给出结果的代码,但有时当我尝试实现另一个代码时结果不正确,我实现的数组给了我最好的结果。我想找到与我在数组中搜索的单词最接近的匹配项,如果我搜索的单词在数组中包含该单词的一些字符,告诉我这个单词是否是我的意思?但在数据库中已经按字母排列。我想在数据库中解决这个问题,以数组形式给出结果,这是我的 index.php

<html>
<body>
<form method="post" action="me.php">
Search :  =<input type="text" name="name" id="x" autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search">
</form>
</html>

这是我的数据库代码me.php

<?php

        $input = $_POST['name'];
        if( mysql_connect("localhost" , "root" , "") &&
            mysql_select_db("test") )
        {
            echo 'connected<br>';
        }
        else
        {
            echo 'Failed';
        }

        if( $query_run = mysql_query("SELECT * FROM `table` WHERE `mytext` LIKE '%$input%'") )
        {
            if(mysql_num_rows($query_run) > 0)
            {
                while( $result = mysql_fetch_assoc($query_run) )
                {
                    $sender = $result['id'] ;
                    $message = $result['mytext'] ;

                    echo "<br>      &nbsp;&nbsp;&nbsp;&nbsp; From: $sender:&nbsp;
                             $message<br>";
                }
            }
            else
            {
                echo 'Bad KeyWord';
            }

        }
        else
        {
            return false ;
        }
?>

这是我的数组代码two.php

<?php

$input = $_POST["name"];
$words  = array('apple','pineapple','banana','orange',
                'radish','anything','carrot','pea','bean','potato');
$shortest = -1;
foreach ($words as $word) {
    if ($input == $word) {
        $closest = $word;
        $shortest = 0;
        break;
    }
    $lev = levenshtein($input, $word);
    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";
}
?>

请帮我解决这个问题

最佳答案

检查这个Levenshtein distance您可以找到可以帮助您的实现。

关于php - 查找拼写最接近的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583846/

相关文章:

php - 来自带有 RequestBody 的 swagger post 调用的空响应

php - 包含或需要的文件是通过互联网传输还是仅在服务器上访问?

php - ffmpeg 和 php - 生成缩略图

mysql - BLToolKit:如何获取 'empty' 日期时间字段?

php - 使用php在sql查询中的where条件中传递数组

php - 在选项标签中显示空格

mysql - 如何在 MySQL 中对行求和

mysql - 更新记录(如果存在);否则插入

javascript - 推送到数组的数据不会保留在数组中

c# - 将 outlook rtfbody 添加到包含其图像的 richtextbox