php preg_replace,正则表达式

标签 php regex preg-replace

我正在尝试使用 php 和 preg_replace 从 yell.com 中提取邮政编码。 我成功提取了邮政编码,但只提取了地址。这是一个例子

$URL = "http://www.yell.com/ucs/UcsSearchAction.do?scrambleSeed=17824062&keywords=shop&layout=&companyName=&location=London&searchType=advance&broaderLocation=&clarifyIndex=0&clarifyOptions=CLOTHES+SHOPS|CLOTHES+SHOPS+-+LADIES|&ooa=&M=&ssm=1&lCOption32=RES|CLOTHES+SHOPS+-+LADIES&bandedclarifyResults=1";

//get yell.com page in a string $htmlContent = $baseClass->getContent($URL); //get postal code along with the address $result2 = preg_match_all("/(.*)</span>/", $htmlContent, $matches);

print_r($matches);

上面的代码输出类似 Array ( [0] => Array ( [0] => 7, Royal Parade, Chislehurst, Kent BR7 6NR [1] => 55, Monmouth St, London, WC2H 9DG ....我的问题是我不知道如何只提取没有地址的邮政编码,因为它没有确切的位数(有时它有 6 位数字,有时只有 5 次)。基本上我应该从每个数组中提取最后的 2 个单词. 提前感谢您的帮助!

最佳答案

快速而肮脏:

# your array item
$string = "7, Royal Parade, Chislehurst, Kent BR7 6NR";

# split on spaces
$bits = preg_split('/\s/', $string);

# last two bits
end($bits);
$postcode = prev($bits) . " " . end($bits);

echo $postcode;

查看它在以下位置运行:code pad

关于php preg_replace,正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2842533/

相关文章:

regex - 如何确定字符串是否包含R中的非罗马字符

Python 比较列表中的部分字符串

php - 正则表达式删除外括号

php - 如何从 PHP 中的字符串中删除多个单词?

javascript - 单击两个链接,执行某些操作吗?

php - 从 HTTP 重定向到 HTTPS(最好的方法是 .htaccess 或 PHP 重定向代码)

php - PHP foreach 循环中的数组范围

需要 Python 正则表达式解释 - $ 字符用法

php - 单击导航栏中的选项时更改 $sql

javascript - 如何使用 JavaScript 删除 html 标签并保留换行符?