云迈博客

您现在的位置是:首页 > 后端开发 > PHP > 正文

PHP

通过通讯地址匹配获取 省 市 区

caocan2022-09-26PHP35
通过通讯地址获取相对于的省市区functionget_address($address){preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|
通过通讯地址获取相对于的省市区
function get_address($address){
    preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
    if (count($matches) > 1) {
        $province = $matches[count($matches) - 2];
        $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/','', $address, 1);
    }
    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 : '',
        'district' => isset($area) ? $area : '',
        "address" => $address
    ];
}

$ress=’湖南省长沙市雨花区xxx地方’;
$address=get_address($ress);
返回结果:

Array
(
    [province] => 湖南省
    [city] => 长沙市
    [district] => 雨花区
    [address] => xxx地方
)