Peter Cos Peter Cos -4 years ago 155
PHP Question

Regex to find digits between the last set of parentheses

i was struggling to make a regex which extract the digits bettween the last set of parentheses from a string, and this is what i came with until now:



This is, (123456) a string (78910);

It returns 123456 , which is great but i need it to look at the last set and return 78910.Also , i want the regex to ignore everything but digits:

This is, (123bleah456) a string (789da10);

Should return: 78910


Using regex:


For string:

Telefon Mobil (123)Apple iPhone 6 128GB Gold(1567)asd234

Will return 234 when it should be 1567


Answer Source

You can extract the last one by use of greed:


See demo at regex101

\K resets beginning of the reported match.

For your more specific updated case slightly modifiy the regex and strip out non-digits.

$str = "This is, (123bleah456) a string (789da10);";

if(preg_match('/.*\(\K\d[^)]*/', $str, $out))
  $res = preg_replace('/\D+/', "", $out[0]);

See demo at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download