jcubic jcubic - 2 months ago 4
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


so far I have


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


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


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


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