levenshtein
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
levenshtein - 计算两个字符串之间的Levenshtein距离
描述
int levenshtein ( string $str1 , string $str2 )
int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )
Levenshtein距离定义为:您必须替换,插入或删除以将str1转换为str2的最小字符数。 算法的复杂度为O(m * n),其中n和m是str1和str2的长度(与similar_text()相比较好,即O(max(n,m)** 3) 仍然代价较高)。
在其最简单的形式中,函数将只接受两个字符串作为参数,并且将计算将str1转换为str2所需的插入,替换和删除操作的次数。
第二个变体将采用另外三个参数来定义插入,替换和删除操作的成本。这比变种更具普遍性和适应性,但效率不高。
参数
str1
其中一个字符串正在评估Levenshtein距离。
str2
其中一个字符串正在评估Levenshtein距离。
cost_ins
定义插入的成本。
cost_rep
定义替换的成本。
cost_del
定义删除的成本。
返回值
如果其中一个参数字符串长于255个字符的限制,此函数返回两个参数字符串之间的Levenshtein-Distance或-1。
例子
示例#1 levenshtein()示例
<?php
//?input?misspelled?word
$input?=?'carrrot';
//?array?of?words?to?check?against
$words??=?array('apple','pineapple','banana','orange',
????????????????'radish','carrot','pea','bean','potato');
//?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";
}
?>
上面的例子将输出:
Input word: carrrot
Did you mean: carrot?
扩展内容
- soundex() - 计算字符串的soundex键
- similar_text() - 计算两个字符串之间的相似度
- metaphone() - 计算字符串的metaphone键值
← lcfirst
localeconv →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com