テストエントリの小さなセットであなたのコードを試してみたところ、うまくいきました。クエリから奇妙な結果が得られたのではないでしょうか? コードは次のとおりです。
$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 関数は、similar_text よりもパフォーマンスの点でコストがかかりませんが、結果をパーセントで返しません!
レーベンシュタインアプローチのコード:
$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'];