【发布时间】: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> From: $sender:
$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”。您可以找到适合 MySQL 的实现,它可能会解决您的问题。
-
我搜索它但找不到任何链接解决我的问题如果你能帮助我@GordonLinoff
标签: php mysql arrays autocomplete autocorrect