奇怪的回归与正则表达式

时间:2013-08-12 08:31:47

标签: php regex

我有一个这样的字符串:

$somestring= "10, Albalala STREET 11 (768454)";

for mat可能会改变一点:

$somestring= "10, Albalala STREET 11 (S) 768454 ";

$somestring= "10, Albalala STREET 11 (S) ( 768454 )";

我想在php中使用正则表达式来获取该6位数字(这是邮政编码)。

$regex_pattern = "/^\d{6}$/";
preg_match_all($regex_pattern,$somestring,$matches);
print_r("postalcode: " . $matches);//

我得到的结果是:

postalcode: Array

不是数字768454 你知道为什么吗?

2 个答案:

答案 0 :(得分:1)

由于^$,正则表达式不匹配。而是使用\b(字边界)。

要仅获取数字,请通过$matches[0][0]访问它:

$somestring= "10, Albalala STREET 11 (768454)";
$regex_pattern = "/\b\d{6}\b/";
preg_match_all($regex_pattern, $somestring, $matches);
print_r($matches[0][0]); # => 768454

答案 1 :(得分:0)

试试这个

$a = '10, Albalala STREET 11 (S) ( 768454 )';
$a = preg_replace('/\D{1,}$/', '', $a); // remove non digit chars at the end
preg_match_all('/\d{6}$/',$a,$matches);
$val = $matches[0];
print_r("postalcode: " . $val[0]);//
相关问题