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

PHP uses regular expressions to match provinces and cities

php中世界最好的语言
Release: 2023-03-26 06:54:01
Original
4117 people have browsed it

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);
Copy after login

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template