Reputation: 1631
I'm trying to write a regex to be used in PHP to match the arguments of a specific function. Here's an example of the kind of things I'm trying to match:
$content = "myfunction('Text with (nested) parentheses')
myfunction('Text2 without nested parentheses')
myfunction('Text2 with variables ' + myvar)
myfunction(myvar)
myfunction(myvar1 + \"(nested) some text here\" + (error.length ? \" \" + errorMsg : \"\"))";
preg_match_all('/myfunction\(([^()]|(?R))*\)/', $content, $matches);
As you can imagine, all return except the one with the nested parentheses. The |(?R) is what I would expect would make it work. If I do this, however, things work as expected:
$content = "('Text with (nested) parentheses')
('Text2 without nested parentheses')
('Text2 with variables ' + myvar)
(myvar)";
preg_match_all('/\(([^()]|(?R))*\)/', $content, $matches);
Unfortunately, I need to have the function name because I only want to match one specific function. Is that doable with a regex?
Upvotes: 1
Views: 60
Reputation: 424953
Use a look ahead to exclude matching on close brackets when within quotes:
myfunction\((.*?)\)(?=(([^'"]*['"]){2})*[^'"]*$)
See live demo.
This says "match a closing bracket that is followed by an even number of quotes" (recalling that zero is an "even" number). Characters within quotes have an odd number of quotes after them.
The reluctant quantifier *?
will stop at the first such match, in case you have multiple matches on the same line.
Upvotes: 3