這次給大家帶來PHP利用Regex匹配省市區,PHP利用Regex匹配省市區的注意事項有哪些,下面就是實戰案例,一起來看一下。
preg_match('/(.*?(省|自治區|北京市|天津市))+(.*?(市|自治州|地區|區劃|縣))+(.*?(區|縣|鎮|鄉|街道))/', $address, $matches);
獲得省市區數組
$address = '廣東省深圳市南山區';preg_match('/(.*?(省|自治區|北京市|天津市))/', $address, $matches);if (count($matches) > 1) { $province = $matches[count($matches) - 2]; $address = str_replace($province, '', $address);}preg_match('/(.*?(市|自治州|地區|區劃|縣))/', $address, $matches);if (count($matches) > 1) { $city = $matches[count($matches) - 2]; $address = str_replace($city, '', $address);}preg_match('/(.*?(區|縣|鎮|鄉|街道))/', $address, $matches);if (count($matches) > 1) { $area = $matches[count($matches) - 2]; $address = str_replace($area, '', $address);}return [ 'province' => isset($province) ? $province : '', 'city' => isset($city) ? $city : '', 'area' => isset($area) ? $area : '',];
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
phpmailer使用php發郵件案例解析
php無限級評論嵌套實現步驟詳解