我正在尝试在我的网络应用程序中实现搜索功能,我想做的是在数据库中搜索一个单词,如果它不存在,系统应该告诉我或找到与该单词最接近的匹配项。我实现了在数据库中搜索并给出结果的代码,但有时当我尝试实现另一个代码时结果不正确,我实现的数组给了我最好的结果。我想找到与我在数组中搜索的单词最接近的匹配项,如果我搜索的单词在数组中包含该单词的一些字符,告诉我这个单词是否是我的意思?但在数据库中已经按字母排列。我想在数据库中解决这个问题,以数组形式给出结果,这是我的 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您可以找到可以帮助您的实现。
关于php - 查找拼写最接近的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583846/