Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

I am working on a 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]*(?!->))/

Unfortunately, this pattern matches $fo. See this regex demo.

like image 919
jcubic Avatar asked Jun 24 '26 17:06

jcubic


1 Answers

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

like image 145
Wiktor Stribiżew Avatar answered Jun 26 '26 09:06

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!