levenshtein

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

levenshtein锟斤拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷之锟斤拷谋嗉拷锟斤拷锟�

说锟斤拷

levenshtein ( string $str1 , string $str2 ) : int
levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) : int

锟洁辑锟斤拷锟诫,锟斤拷指锟斤拷锟斤拷锟街达拷之锟戒,通锟斤拷锟芥换锟斤拷锟斤拷锟诫、删锟斤拷锟饺诧拷锟斤拷锟斤拷锟街凤拷锟斤拷str1转锟斤拷锟斤拷str2锟斤拷锟斤拷要锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷锟斤拷锟斤拷 锟斤拷锟姐法锟侥革拷锟接讹拷锟斤拷 O(m*n)锟斤拷锟斤拷锟斤拷 n 锟斤拷 m 锟街憋拷锟斤拷str1 锟斤拷str2锟侥筹拷锟斤拷 锟斤拷锟斤拷锟斤拷锟姐法锟斤拷锟接讹拷为O(max(n,m)**3)锟斤拷similar_text()锟斤拷锟绞憋拷锟斤拷撕锟斤拷锟斤拷锟斤拷锟斤拷嗟憋拷锟斤拷锟侥o拷锟斤拷锟斤拷锟斤拷然锟杰猴拷时锟斤拷锟斤拷锟斤拷

锟斤拷锟斤拷虻サ锟斤拷锟绞斤拷校锟斤拷煤锟斤拷锟街伙拷锟斤拷锟斤拷锟斤拷址锟斤拷锟斤拷锟轿拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟酵拷锟斤拷锟斤拷搿拷婊伙拷锟缴撅拷锟斤拷炔锟斤拷锟斤拷锟�str1转锟斤拷锟斤拷str2锟斤拷锟斤拷要锟侥诧拷锟斤拷锟斤拷锟斤拷锟斤拷

锟节讹拷锟街憋拷锟藉将锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷牟锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟诫、锟芥换锟斤拷删锟斤拷锟斤拷锟斤拷锟侥达拷锟斤拷锟斤拷锟剿憋拷锟斤拷鹊锟揭伙拷指锟斤拷锟酵拷煤锟斤拷锟接︼拷锟斤拷锟叫э拷什锟斤拷摺锟�

锟斤拷锟斤拷

str1

锟斤拷嗉拷锟斤拷锟斤拷械锟斤拷锟斤拷锟揭伙拷锟斤拷址锟斤拷锟�

str2

锟斤拷嗉拷锟斤拷锟斤拷械锟斤拷锟揭伙拷锟斤拷址锟斤拷锟�

cost_ins

锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷

cost_rep

锟斤拷锟斤拷锟芥换锟斤拷锟斤拷

cost_del

锟斤拷锟斤拷删锟斤拷锟斤拷锟斤拷

锟斤拷锟斤拷值

锟剿猴拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷锟斤拷锟斤拷之锟斤拷谋嗉拷锟斤拷耄拷锟斤拷锟斤拷锟斤拷一锟斤拷锟街凤拷锟斤拷锟斤拷锟斤拷锟斤拷锟饺达拷锟斤拷锟斤拷锟狡碉拷255锟斤拷锟街凤拷时锟斤拷锟斤拷锟斤拷-1锟斤拷

锟斤拷锟斤拷

Example #1 levenshtein() 锟斤拷锟接o拷

<?php
// 锟斤拷锟斤拷拼写锟斤拷锟斤拷牡锟斤拷锟�
$input 'carrrot';

// 要锟斤拷锟侥碉拷锟斤拷锟斤拷锟斤拷
$words  = array('apple','pineapple','banana','orange',
                
'radish','carrot','pea','bean','potato');

// 目前没锟斤拷锟揭碉拷锟斤拷叹锟斤拷锟�
$shortest = -1;

// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟揭碉拷锟斤拷咏锟斤拷锟�
foreach ($words as $word) {

    
// 锟斤拷锟斤拷锟斤拷锟诫单锟斤拷锟诫当前锟斤拷锟绞的撅拷锟斤拷
    
$lev levenshtein($input$word);

    
// 锟斤拷锟斤拷锟饺拷锟狡ワ拷锟�
    
if ($lev == 0) {

        
// 锟斤拷咏锟斤拷牡锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷全匹锟戒)
        
$closest $word;
        
$shortest 0;

        
// 锟剿筹拷循锟斤拷锟斤拷锟斤拷锟斤拷锟窖撅拷锟揭碉拷一锟斤拷锟斤拷全锟斤拷匹锟斤拷
        
break;
    }

    
// 锟斤拷锟斤拷舜尉锟斤拷锟斤拷锟较达拷锟揭碉拷锟斤拷要锟斤拷
    // 锟斤拷锟竭伙拷没锟揭碉拷锟接斤拷锟侥碉拷锟斤拷
    
if ($lev <= $shortest || $shortest 0) {
        
// 锟斤拷锟斤拷锟斤拷咏锟斤拷锟狡ワ拷锟斤拷约锟斤拷锟斤拷锟斤拷锟教撅拷锟斤拷
        
$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() - Calculate the soundex key of a string
  • similar_text() - 锟斤拷锟斤拷锟斤拷锟斤拷锟街凤拷锟斤拷锟斤拷锟斤拷锟狡讹拷
  • metaphone() - Calculate the metaphone key of a string