Peter Cos Peter Cos - 21 days ago 6
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:

^.*?\([^\d]*(\d+)[^\d]*\).*$


E.g.:

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

UPDATE

Using regex:

(\d+)(?!.*\d)


For string:

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


Will return 234 when it should be 1567

Rubular

Answer

You can extract the last one by use of greed:

.*\(\K\d+

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 eval.in

Comments