PHP代码在线运行


<?php date_default_timezone_set('Asia/Shanghai'); $str = '内蒙古自治区锡林郭勒盟西乌珠穆沁旗详细地址详细地址xxx'; function addressSplit($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); } $data = [ 'province' => isset($province) ? $province : '', 'city' => isset($city) ? $city : '', 'area' => isset($area) ? $area : '', 'address' => isset($address) ? $address : '', ]; if ($city == '北京市' || $city == '天津市' || $city == '重庆市' || $city == '上海市') { $data['province'] = $city; } return $data; } $s = addressSplit($str); print_r($s);