jcubic jcubic - 6 months ago 28
PHP Question

How to match php variable but not inside single quoted string

I need to match php variable but not method call, not inside single quote and not if $ is escaped.

is should match:


but not when used like this:

'foo $bar baz'

So far I have this regex:
that don't match method call and escaped dolar demo


You can use this regex in PCRE with verbs (*SKIP) and (*FAIL):


RegEx Breakup:

'[^'\\]*(?:\\.[^'\\]*)*' # will match text between single quotes skipping escaped quotes
(*SKIP)(*F)              # skips above single quoted text
(?<!\\)                  # negative lookbehind to fail the match is $ is preceded by \
[a-zA-Z_]\w*             # will match a variable starting with $, \b is for word boundary
(?!->)                   # negative lookahead to fail the match if -> is at next position

RegEx Demo