如何排序相似度就输入的字的数组。 [英] How to sort an array by similarity in relation to an inputted word.
本文介绍了如何排序相似度就输入的字的数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有PHP阵列上,例如:
I have on PHP array, for example:
$arr = array("hello", "try", "hel", "hey hello");
现在我想做的事情,这将是基于阵列和我的$搜索VAR之间最密切的近字阵列的重新排列。
Now I want to do rearrange of the array which will be based on the most nearly close words between the array and my $search var.
我怎么能这样做?
推荐答案
您可以使用莱文斯坦功能
<?php
// input misspelled word
$input = 'helllo';
// array of words to check against
$words = array('hello' 'try', 'hel', 'hey hello');
// no shortest distance found, yet
$shortest = -1;
// 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;
}
}
echo "Input word: $input\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
?>
这篇关于如何排序相似度就输入的字的数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文