Intelligent parentheses matching with PHP/Regex

Multi tool use
I'd love to highlight a function's use in a block of code.
For example, take a look at the instance of fwrite() in this sample code:
A simple preg_replace, and I can highlight that function:
However, in the event that the function contains nested parentheses, it gets trickier.
If the code sample, instead was:
... then the regex pattern won't know that the content inside the fwrite() function isn't the closing of the function.
EDIT:
I tried using the solution offered by @patrick-q with "eval()" in the following sample, and it didn't match as expected:
...ram]").attr("content");C&&B&&(k.extraData=k.extraData||{},k.extraData[C]=B),k.forceSync?g():setTimeout(g,10);var D,E,F,G=50,H=a.parseXML||function(a,b){return window.ActiveXObject?(b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a)):b=(new DOMParser).parseFromString(a,"text/xml"),b&&b.documentElement&&"parsererror"!==b.documentElement.nodeName?b:null},I=a.parseJSON||function(a){return window.eval("("+a+")")},J=function(b,c,d){var e=b.getResponseHeader("content-type")||"",f=("xml"===c||!c)&&e.indexOf("xml")>=0,g=f?b.responseXML:b.responseText;return f&&"parsererror"===g.documentElement.nodeName&&a.error&&a.error("parsererror"),d&&d.dataFilter&&(g=d.dataFilter(g,c)),"string"==typeof g&&(("json"===c||!c)&&e.indexOf("...
Demo with eval();
In the second example, it is stopping at the first )
(parenthesis) because you have the U
(ungreedy) flag on your expression. So instead of the default behavior of matching as much as possible, it is now "lazy" and matches as little as possible. To resolve this, simply remove the U
flag.
Then we have to address the fact that your first example excludes the ;
(semi-colon) from the match. This is because you have the ?
quantifier which matches the preceding character 0 or 1 times in a lazy (as few as possible, including zero) manner. To get this behavior after removing the U
flag, we have to add a second ?
which then flips the default behavior from greedy to lazy.
Put these together and you should get this:
DEMO
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.