Home >Backend Development >PHP Tutorial >An explanation of how to simply implement regular matching of provinces and cities in PHP
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 it
This article describes PHP with examples 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(' /(.*?(Province|Autonomous Region|Beijing City|Tianjin City)) (.*?(City|Autonomous Prefecture|Region|Division|County)) (.*?(District|County|Town|Township|Street))/ ', $address, $matches);
Get the province and city 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, comments are welcome Leave a message
PS: Here are two 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
PHP Closure Definition and Use Simple Example PHP Skills
php WeChat Public Account Development Cash Red Packet PHP Example
PHP code reconstruction method talk_php skills
The above is the detailed content of An explanation of how to simply implement regular matching of provinces and cities in PHP. For more information, please follow other related articles on the PHP Chinese website!