How does PHP match the most similar strings in a string pool? This paper mainly introduces the method of PHP query the most similarity of the string, involving PHP operation string and array to implement the similarity algorithm skills, I hope to be helpful to everyone.
Returns the most similar string in the array, based on the strings and arrays passed in
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. The code example is as follows:
Returns the state name with the highest similarity, based on the incoming state name (which may have been lost by the customer) $united_state_list = Array (' AL ' = ' Alabama ', ' AK ' = ' Alaska ', ' AZ ' = ' Arizona ' , ' AR ' = ' Arkansas ', ' CA ' = ' California ', ' CO ' = ' Colorado ', ' CT ' = ' Connecticut ', ' DE ' and ' Delaware ', ' DC ' = "District of Columbia", ' FL ' = ' Florida ', ' GA ' = ' Georgia ', ' HI ' and ' Hawaii ', ' ID ' and ' Idaho ', ' IL ' and ' = ' Illinois ", ' in ' + ' Indiana", ' IA ' = ' Iowa ', ' KS ' = ' Kansas ', ' KY ' = ' Kentucky ', ' LA ' and ' Louisiana ', ' ME ' = > "Maine", ' MD ' = ' Maryland ', ' MA ' = ' Massachusetts ', ' MI ' = ' Michigan ', ' MN ' = ' Minnesota ', ' MS ' and ' = ' Mississippi ", ' MO ' =" Missouri ", ' MT ' = ' Montana ', ' NE ' = ' Nebraska ', ' NV ' and ' Nevada ', ' NH ' = ' New ' Hampshire ", ' NJ ' =" New Jersey ", ' NM ' = ' new Mexico ', ' NY ' = ' new York ', ' NC ' = ' North Carolina ', ' ND ' = ' North Dakota ", ' OH ' and" Ohio ", ' OK ' and ' Oklahoma ', ' OR ' = ' Oregon ', ' PA ' and ' Pennsylvania ', ' RI ' = ' Rhode ' Island ", ' SC ' =" South Carolina ", ' SD ' = ' South Dakota ', ' TN ' = ' Tennessee ', ' TX ' = ' Texas ', ' UT ' = ' Utah ', ' VT ' = ' vermOnt ", ' VA ' = ' Virginia ', ' WA ' = ' Washington ', ' WV ' = ' West Virginia ', ' WI ' = ' Wisconsin ', ' WY ' and ' Wyoming ' ); $input _state = ' Wiscsin '; $state = Closest_word ($input _state, array_values ($united _state_list)); Echo $state;
Related recommendations:
Introduction to PHP string segmentation and comparison
A detailed description of the PHP string function
PHP String Common functions