Home  >  Article  >  Backend Development  >  PHP uses regular expressions to match provinces and cities

PHP uses regular expressions to match provinces and cities

php中世界最好的语言
php中世界最好的语言Original
2018-05-16 16:00:084011browse

This time I will bring you PHP usageRegular expressionsmatching provinces and cities, PHP using regular expressions to match provinces and citiesWhat are the precautionsWhat are the practical cases below? , let’s take a look.

preg_match('/(.*?(省|自治区|北京市|天津市))+(.*?(市|自治州|地区|区划|县))+(.*?(区|县|镇|乡|街道))/', $address, $matches);

Get the array of provinces and cities

$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 : '',
];

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

phpmailer uses php to send emails case analysis

php unlimited comment nesting implementation steps detailed explanation

The above is the detailed content of PHP uses regular expressions to match provinces and cities. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn