1

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)]]'
0

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Try this one:

    $input="input([[1,2,nc(2)],[1,2,nc(1)]])";
    preg_match('/input\((.*?\]\])\)/',$input,$matches);
    print_r($matches);

$matches[1] will contain whole result you need. Hope this works.

Comments

1

You want it purely as a string? Use this simple regex:

preg_match('/\((.*)\)$/',$input,$matches);

Comments

1

None of the other answers have efficiently/accurately answered your question:

For the fastest accurate pattern, use:

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo preg_match('/input\((.*)\)/i',$input,$output)?$output[1]:'';
//                                            notice index ^

Or a slightly slower pattern that uses 50% less memory by avoiding the capture group, use:

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo preg_match('/input\(\K(.*)(?=\))/i',$input,$output)?$output[0]:'';
//                                                  notice index ^

Both methods will provide the same output: [[1,2,nc(2)],[1,2,nc(1)]]

Using a greedy * quantifier allows the pattern to move passed the nested parentheses and match the entire intended substring.

In the second pattern, \K resets the match's starting point and (?=\)) is a positive lookahead that ensures the entire substring is matched without including the trailing closing parenthesis.


EDIT: All that regex convolution aside, because you know your desired substring is wrapped in input( and ), the best, simplest approach is a non-regex one...

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo substr($input,6,-1);
// output: [[1,2,nc(2)],[1,2,nc(1)]]

Done.

1 Comment

@Gamsh I added an even simpler method. See my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.