PHP 匹配一个字符串

标签 php

我有一个印度公司数据集,需要从地址字段中提取城市和邮政编码:

地址字段示例: Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, 印度

如您所见,城市是 Karur,zip 紧跟在 -(连字符)之后。

我需要 PHP 代码来匹配 [city] - [zip]

不确定如何执行此操作我可以在 Hypen 之后找到 Zip 但不确定如何找到城市,请注意城市可以是 2 个单词。

为你的时间干杯。/

J

最佳答案

试试这个:

<?php
$address = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

// removes spaces between digits.
$address = preg_replace('{(\d)\s+(\d)}','\1\2',$address);

// removes spaces surrounding comma.
$address = preg_replace('{\s*,\s*}',',',$address);
var_dump($address);

// zip is 6 digit number and city is the word(s) appearing betwwen zip and previous comma.
if(preg_match('@.*,(.*?)(\d{6})@',$address,$matches)) {
    $city = trim($matches[1]);
    $zip = trim($matches[2]);
}

$city = preg_replace('{\W+$}','',$city);

var_dump($city);    // prints Karur
var_dump($zip);     // prints 639002

?>

关于PHP 匹配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2364176/

相关文章:

php - 从 MySQL 数据库中插入和选择

php - 是否有任何用于 PHP 的开源文本分析库?

php - 使用 PHP 重新排序 mysql 行

php - 如何使用 php 和 mysql 制作组合框?

php - 包罗万象的MySQL数据验证

php - 全局通知的数据库设计

php - sql数据库中eloquent laravel中文支持

javascript - getElementByID div 标签内的 PHP echo 语句

php - 如何使用 HTML/PHP 防止 XSS?

php - 如何在 WooCommerce 中编辑 "woocommerce_thankyou"钩子(Hook)的输出?