Home  >  Article  >  Backend Development  >  A simple method to implement regular matching of provinces and cities in PHP

A simple method to implement regular matching of provinces and cities in PHP

不言
不言Original
2018-04-13 11:50:362222browse

This article mainly introduces the method of PHP to simply implement regular matching of provinces and cities, involving PHP regular matching, judgment, calculation and other related operating skills. Friends in need can refer to the following

The examples of this article describe PHP A simple method to implement regular matching of provinces and cities. Share it with everyone for your reference, the details are as follows:

Province and city regular matching

Copy code The code is as follows:

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

Get the province Urban array

$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 feel there should be a better way, please leave a comment

PS: Here again We provide you with 2 very convenient regular expression tools for your reference:

JavaScript regular expression online testing tool:
http://tools.jb51.net/regex/javascript

Regular expression online generation tool:

http ://tools.jb51.net/regex/create_reg

##Related recommendations:

The reason why PHP regular expression fails to match all characters and the solution

PHP regular expression (add 177 mobile phone number)

The above is the detailed content of A simple method to implement regular matching of provinces and cities in PHP. 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