jcubic jcubic - 3 months ago 7
PHP Question

Regex that will match php variable but not object and function invocation

I need regex that will match one of

$foo $bar $baz


but not

$foo->bar


so far I have

/\$([a-zA-Z_][a-zA-Z_0-9]*(?!->))/


but this match
$fo
. https://regex101.com/r/xT0qC9/1

Answer

Use a possessive quantifier that will disallow backtracking into the [a-zA-Z_0-9] subpattern:

\$([a-zA-Z_][a-zA-Z_0-9]*+(?!->))
                        ^^

or even (as [a-zA-Z_0-9] = \w if you are not using /u modifier or (*UCP) verb):

\$([a-zA-Z_]\w*(?!->))

See regex demo

The issue is that when the negative lookahead fails backtracking gets into play, and as * allows backtracking into the quantified subpattern, the o that is not followed with -> is found and a match is returned.

See how your regex works, pay special attention at the backtracking steps:

enter image description here

Comments