簡體   English   中英

類似的文字php mysql

[英]Similar Text php mysql

我有以下代碼,當我搜索一個單詞時,它向我顯示了您的意思。 問題是如果我輸入“臨床”,我希望它返回臨床,但返回“重新安排”

$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>';

我不熟悉PHP的similar_word() ,但您也可以嘗試以下操作:

http://www.php.net/manual/zh/function.levenshtein.php ,這是一種用於執行所需搜索類型的流行算法。

我只是用一小組測試條目嘗試了您的代碼,但效果很好。 也許您從查詢中得到奇怪的結果? 這是代碼:

$my_word = $_REQUEST['value'];
$bestMatch = array('word' => $my_word, 'match' => 2);
$result = array("exam", "clinicals", "templates", "reschedule", "crafting", "php", "answer");
$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函數在性能上的花費不如same_text,但是它不會以百分比返回結果!

levenshtein方法的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM