phpregexsubstringpreg-matchsquare-bracket

How to capture an array-formatted substring from a string


I want to get an array-formatted substring which is inside of the input(). I used preg_match but can't get the entire expression. It is stopping at the first ). How can I match the entire substring? Thank You.

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('@^([^[]+)?([^)]+)@i',$input, $output); 

Expectation is:

'[[1,2,nc(2)],[1,2,nc(1)]]'

Solution

  • This pattern match your desired string (also with starting word ≠ ‘input’:

    @^(.+?)\((.+?)\)$@i
    

    3v4l.org demo

    ^(.+?)   => find any char at start (ungreedy option)
    \)       => find one parenthesis 
    (.+?)    => find any char (ungreedy option) => your desired match
    \)       => find last parenthesis