Returns the string with the highest similarity in the array based on the input string and array.
function closest_word($input, $words) {$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; }}return $closest;}
2. [code] Sample code
// Return the highest similarity state name $ united_state_list = array ('Al' => "Alabama ", 'AK' => "Alaska", 'az' => "Arizona", 'ar '=> "Arkansas", 'CA' => "California ", 'Co' => "Colorado", 'CT '=> "Connecticut", 'DE' => "Delaware", 'DC' => "District Of Columbia ", 'fl '=> "Florida", 'Gal' => "Georgia", 'hi' => "Hawaii", 'id' => "Idaho ", 'il '=> "Illinois", 'in' => "Indiana", 'ia' => "Iowa", 'K' => "Kansas ", 'ky '=> "Kentucky", 'La' => "Louisiana", 'me' => "Maine", 'MD' => "Maryland ", 'ma' => "Massachusetts", 'MI' => "Michigan", 'mn '=> "Minnesota", 'Ms' => "Mississippi ", 'Mo' => "Missouri", 'mt' => "Montana", 'ne '=> "Nebraska", 'nv' => "Nevada ", 'NH '=> "New Hampshire", 'NJ' => "New Jersey", 'nm '=> "New Mexico", 'ny' => "New York ", 'NC '=> "North Carolina Lina", 'nd' => "North Dakota", 'oh' => "Ohio",' OK '=> "Oklahoma ", 'OR' => "Oregon", 'pa' => "Pennsylvania", 'Ri' => "Fig Island", 'scs' => "South Carolina Lina ", 'SD' => "South Dakota", 'tn' => "Tennessee", 'tx '=> "Texas", 'ut' => "Utah ", 'vt '=> "Vermont", 'VA' => "Virginia", 'wa '=> "Washington", 'wv' => "West Virginia ", 'WY' => "Wisconsin", 'WY' => "Wyoming"); $ input_state = 'wiscsin '; $ state = closest_word ($ input_state, array_values ($ united_state_list); echo $ state;
The above is the content of the string with the highest similarity. For more information, see The PHP Chinese website (www.php1.cn )!