Search code examples
phpregexintegerpreg-matchparentheses

How to get a number wrapped in parentheses from a string?


I have this code

$string = "23 asdasdasdasd.sma(33) asda sdas asd 23 2 3 54232 23d asd";

$reg = "??";
preg_match($reg, $string, $matches);
var_dump($matches);

I want to get this number: 33.


Solution

  • Because you are calling preg_match() in your code and your input data only has one target number available, you can accurately use this fastest/briefest pattern:

    ~\(\K\d+~ (Pattern Demo) (5 steps & no capture groups & no lookarounds)

    Pattern Breakdown:

    ~        #pattern delimiter
    \(       #match (
    \K       #restart the fullstring match (forget previously matched characters)
    \d+      #match one or more digits greedily
    ~        #pattern delimiter
    

    *to be clear, I want to state that I my pattern assumes that the number that immediately follows the ( WILL BE followed by a ). This is what the sample input provides.

    If the ) needs to be matched to maintain accuracy, then a capture group (Tim's way) will be the next most efficient way. All correct patterns that use lookarounds will be slower than correct patterns without.