奇怪的回归与正则表达式

I have a string like this :

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

the for mat could change a little bit like :

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

or

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

I want to use regex in php to get that 6 digits number (which is the postal code).

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

The result I got is :

postalcode: Array

not a number 768454 Do you have any idea why ?

Regular expression does not match because of ^ and $. Instead use \b (word boundary).

To get only the digits, access it by $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

try this

$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]);//