PHP Simple Method for Regular Matching of Provinces and Cities

  • 2021-09-20 19:36:50
  • OfStack

In this paper, an example is given to describe the simple method of regular matching between provinces and cities by PHP. Share it for your reference, as follows:

Regular matching of provinces and cities

preg_match('/(.*?( Province | Autonomous Region | Beijing | Tianjin ))+(.*?( City | Autonomous prefecture | Region | Division | County ))+(.*?( District | County | Town | Township | Street ))/', $address, $matches);

Get an array of provinces and cities


$address = ' Nanshan District, Shenzhen City, Guangdong Province ';
preg_match('/(.*?( Province | Autonomous Region | Beijing | Tianjin ))/', $address, $matches);
if (count($matches) > 1) {
  $province = $matches[count($matches) - 2];
  $address = str_replace($province, '', $address);
}
preg_match('/(.*?( City | Autonomous prefecture | Region | Division | County ))/', $address, $matches);
if (count($matches) > 1) {
  $city = $matches[count($matches) - 2];
  $address = str_replace($city, '', $address);
}
preg_match('/(.*?( District | County | Town | Township | Street ))/', $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 that there should be a better way. Welcome to comment and leave a message

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

For more readers interested in PHP related contents, please check the topics on this site: "Summary of php Regular Expression Usage", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: