Tell RegEx to ignore parenthesis when inside a quote

Viewed 341

I have the following RegEx that is used and works:

/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?/x

Where this string @extends('template', 'test') correctly groups and gives me what I need.

The problem is if the string contains an unclosed parenthesis inside the quotes - it will fail:

@extends('template', 'te)st') gives @extends('template', 'te) as the output

How can I tell this RegEx to ignore parenthesis that are inside quotes (either ' or ")

Here is a RegExr demo of the problem: http://regexr.com/v1?396ci

And here is a list of strings that should all be able to pass:

@extends('template', 'test')     // working
@extends('template', $test)      // working
@extends('template', 'te()st')   // working
@extends('template', 'te)st')    // broken 
@extends('template', 'te())st')  // broken
@extends('template', 'te(st')    // broken
@extends('template', 'test)')    // broken
@extends('template', '(test')    // broken

I've narrowed it down - and I think I need to be able to say

(
   \(  <-- only if not inside quotes
     ( 
         (?>[^()]+) | (?3) 
     )* 
   \) <-- only if not inside quotes  
)?

But I cant seem to work out how to apply that rule to these specific parenthesis

1 Answers
Related