首頁 >後端開發 >php教程 >php操作字串及陣列實作相似度演算法

php操作字串及陣列實作相似度演算法

墨辰丷
墨辰丷原創
2018-06-12 17:07:192138瀏覽

這篇文章主要介紹了php查詢相似度最高的字符串的方法,涉及php操作字符串及數組實現相似度算法的技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了php查詢相似度最高的字串的方法。具體如下:

根據傳入的字串和數組,傳回數組中相似度最高的字串

1. PHP程式碼如下:    

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. 程式碼範例如下:

// 根据传入的州名(可能客户有输错),返回相似度最高的州名称
$united_state_list = array(
&#39;AL&#39;=>"Alabama",
&#39;AK&#39;=>"Alaska",
&#39;AZ&#39;=>"Arizona",
&#39;AR&#39;=>"Arkansas",
&#39;CA&#39;=>"California",
&#39;CO&#39;=>"Colorado",
&#39;CT&#39;=>"Connecticut",
&#39;DE&#39;=>"Delaware",
&#39;DC&#39;=>"District Of Columbia",
&#39;FL&#39;=>"Florida",
&#39;GA&#39;=>"Georgia",
&#39;HI&#39;=>"Hawaii",
&#39;ID&#39;=>"Idaho",
&#39;IL&#39;=>"Illinois",
&#39;IN&#39;=>"Indiana",
&#39;IA&#39;=>"Iowa",
&#39;KS&#39;=>"Kansas",
&#39;KY&#39;=>"Kentucky",
&#39;LA&#39;=>"Louisiana",
&#39;ME&#39;=>"Maine",
&#39;MD&#39;=>"Maryland",
&#39;MA&#39;=>"Massachusetts",
&#39;MI&#39;=>"Michigan",
&#39;MN&#39;=>"Minnesota",
&#39;MS&#39;=>"Mississippi",
&#39;MO&#39;=>"Missouri",
&#39;MT&#39;=>"Montana",
&#39;NE&#39;=>"Nebraska",
&#39;NV&#39;=>"Nevada",
&#39;NH&#39;=>"New Hampshire",
&#39;NJ&#39;=>"New Jersey",
&#39;NM&#39;=>"New Mexico",
&#39;NY&#39;=>"New York",
&#39;NC&#39;=>"North Carolina",
&#39;ND&#39;=>"North Dakota",
&#39;OH&#39;=>"Ohio",
&#39;OK&#39;=>"Oklahoma",
&#39;OR&#39;=>"Oregon",
&#39;PA&#39;=>"Pennsylvania",
&#39;RI&#39;=>"Rhode Island",
&#39;SC&#39;=>"South Carolina",
&#39;SD&#39;=>"South Dakota",
&#39;TN&#39;=>"Tennessee",
&#39;TX&#39;=>"Texas",
&#39;UT&#39;=>"Utah",
&#39;VT&#39;=>"Vermont",
&#39;VA&#39;=>"Virginia",
&#39;WA&#39;=>"Washington",
&#39;WV&#39;=>"West Virginia",
&#39;WI&#39;=>"Wisconsin",
&#39;WY&#39;=>"Wyoming"
);
$input_state = &#39;Wiscsin&#39;;
$state = closest_word($input_state ,array_values($united_state_list));
echo $state;

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

PHP版QQ登入口

#PHP的三元運算子

php針對陣列的定義、遍歷及刪除

以上是php操作字串及陣列實作相似度演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn