# 从完整地址中截取省市区 地址示例: ``` 北京市海淀区东北旺西路8号院35号楼5层501室 array(3) { ["province"] => string(9) "北京市" ["city"] => string(9) "北京市" ["area"] => string(9) "海淀区" } 贵州省遵义市习水县发展大道 array(3) { ["province"] => string(9) "贵州省" ["city"] => string(9) "遵义市" ["area"] => string(9) "习水县" } 贵州省遵义市赤水市旺隆镇 array(3) { ["province"] => string(9) "贵州省" ["city"] => string(9) "遵义市" ["area"] => string(9) "赤水市" } 四川省成都市金牛区王二火锅 array(3) { ["province"] => string(9) "四川省" ["city"] => string(9) "成都市" ["area"] => string(9) "金牛区" } ``` ## 代码 ```php /** * 截取省市区 * * @param string $address 完整地址 * @return array [province=>'', city=>'', area=>''] */ function splitAddress($address = '重庆市海淀区东北旺西路8号院35号楼5层501室') { preg_match('/(.*?(省|自治区|市))/', $address, $matches); if (count($matches) > 1) { $province = $matches[count($matches) - 2]; if (mb_substr($province, mb_strlen($province)-1, 1) != '市') { $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 : '', ]; } ``` ## 参考 - https://www.cnblogs.com/yimingwang/archive/2004/01/13/8855650.html