An explanation of how to simply implement regular matching of provinces and cities in PHP

jacklove
Release: 2023-04-01 20:36:02
Original
1707 people have browsed it

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 codeThe 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 : '', ];
Copy after login

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

Articles you may be interested in:

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!

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!