This article mainly introduces the php method for querying strings with the highest similarity. it involves php's skill in operating strings and arrays to implement similarity algorithms. it has some reference value, for more information about how to query strings with the highest similarity in php, see the example in this article. Share it with you for your reference. The details are as follows:
Returns the string with the highest similarity in the array based on the input string and array.
1. the PHP code is as follows:
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. 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;
I hope this article will help you with php programming.