jcubic jcubic - 3 months ago 7
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:

$foo
"$bar"


but not when used like this:

$foo->bar
'foo $bar baz'
"\$foo"


So far I have this regex:
"/(?<!\\\\)\$(\w*+(?!->))/"
that don't match method call and escaped dolar demo

Answer

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

'[^'\\]*(?:\\.[^'\\]*)*'(*SKIP)(*F)|(?<!\\)\$([a-zA-Z_]\w*)\b(?!->) 

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

Comments