【问题标题】:Find the nearest word in spelling在拼写中找到最近的单词
【发布时间】:2014-04-30 07:13:42
【问题描述】:

我正在尝试在我的 Web 应用程序中实现搜索功能,我想做的是在数据库中搜索一个单词,如果它不存在,系统应该告诉我或找到与该单词最接近的匹配项。我实现了在数据库中搜索并给我结果的代码,但有时当我尝试实现另一个代码时不正确的结果我实现数组给我最好的结果。我想在数组中找到与我在数组中搜索的单词最接近的匹配项,如果我搜索的单词在数组中有一些单词的字符告诉我我的意思是这个词吗?但在数据库中已按字母排列。我想在数据库中解决这个问题,给我作为数组的结果,这是我的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";
}
?>

请帮我解决这个问题

【问题讨论】:

标签: php mysql arrays autocomplete autocorrect


【解决方案1】:

查看此Levenshtein distance,您可以找到可以帮助您的实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 2015-08-15
    • 2020-10-26
    • 1970-01-01
    • 2022-08-18
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多