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)]]'
This pattern match your desired string (also with starting word ≠ ‘input’:
@^(.+?)\((.+?)\)$@i
^(.+?) => find any char at start (ungreedy option)
\) => find one parenthesis
(.+?) => find any char (ungreedy option) => your desired match
\) => find last parenthesis
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.
You want it purely as a string? Use this simple regex:
preg_match('/\((.*)\)$/',$input,$matches);
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.