如何匹配php变量但不匹配单引号字符串

时间:2016-08-29 19:10:28

标签: php regex

我需要匹配php变量而不是方法调用,而不是单引号内部,如果$被转义则不需要。

应匹配:

$foo
"$bar"

但不是这样使用的时候:

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

到目前为止,我有这个正则表达式:"/(?<!\\\\)\$(\w*+(?!->))/"不匹配方法调用和转义dolar demo

1 个答案:

答案 0 :(得分:1)

您可以在PCRE中使用此动词以及动词(*SKIP)(*FAIL)

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

RegEx分手:

'[^'\\]*(?:\\.[^'\\]*)*' # 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