我一直在阅读和测试 php levenshtein中的一些示例。比较 $input 和 $words 输出比较
$input = 'hw r u my dear angel';
// array of words to check against
$words = array('apple','pineapple','banana','orange','how are you',
'radish','carrot','pea','bean','potato','hw are you');
输出
Input word: hw r u my dear angel
Did you mean: hw are you?
比较,删除你在数组中的硬件。
$input = 'hw r u my dear angel';
// array of words to check against
$words = array('apple','pineapple','banana','orange','how are you',
'radish','carrot','pea','bean','potato');
在第二次删除硬件中,您是否在数组输出中
Input word: hw r u my dear angel
Did you mean: orange?
在哪里similar_text()
echo '<br/>how are you:'.similar_text($input,'how are you');
echo '<br/>orange:'.similar_text($input,'orange');
echo '<br/>hw are you:'.similar_text($input,'hw are you');
how are you:6
orange:5
hw are you:6
在第二次比较时,为什么它输出橙色,当你好吗还有 6 个类似的文本,比如你好吗?有什么方法可以改进或更好的方法吗?我也将所有可能的输入保存在数据库中。我应该查询它并存储array
然后用于foreach
获取levenshtein distance
吗?但如果有数百万,那会很慢。
代码
<?php
// input misspelled word
$input = 'hw r u my dear angel';
// array of words to check against
$words = array('apple','pineapple','banana','orange','how are you',
'radish','carrot','pea','bean','potato','hw are you');
// no shortest distance found, yet
$shortest = -1;
$closest = closest($input,$words,$shortest);
echo "Input word: $input<br/>";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
echo '<br/><br/>';
$shortest = -1;
$words = array('apple','pineapple','banana','orange','how are you',
'radish','carrot','pea','bean','potato');
$closest = closest($input,$words,$shortest);
echo "Input word: $input<br/>";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
echo '<br/><br/>';
echo 'Similar text';
echo '<br/>how are you:'.similar_text($input,'how are you');
echo '<br/>orange:'.similar_text($input,'orange');
echo '<br/>hw are you:'.similar_text($input,'hw are you');
function closest($input,$words,&$shortest){
// loop through words to find the closest
foreach ($words as $word) {
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($input, $word);
// check for an exact match
if ($lev == 0) {
// closest word is this one (exact match)
$closest = $word;
$shortest = 0;
// break out of the loop; we've found an exact match
break;
}
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
return $closest;
}
?>