Search code examples
regexpreg-matchpreg-match-all

Get number inside and outsite () sign


I have a string

$string = "10(400)";
preg_match_all('#[:0-9]([:0-9])#', $string, $matches);
print_r($matches);

I try to get

Array ( [0] => 10 [1] => 400 ) 

How to do that thank, I'm is newer with preg thanks


Solution

  • To take all numbers in a string you can use \d+:

    $string = "10(400)";
    preg_match_all('#\d+#', $string, $matches);
    print_r($matches);
    

    Check the working fiddle here.


    The \d in regex is the same as [0-9] which means it will match one digit. When you combine it with the plus sign + it means that all nested digits will be grouped in one match.

    As the preg_match_all will search all matches (obviously).. you do not need to specify the g flag.

    Hope it helps.