Skip to content
Advertisement

PHP reg expression to detect variable in string [closed]

I could never figure out reg expressions, no matter how hard I tried. Need some help pretty please:

I want to be able to find all php variables in a string. for instance:

JavaScript

The thing is that variables can be at the begining/end of line. They may or may not have a space before/after them. There may be a = or a ? or a != or a ( or a ) or < or > or even !$isTrue. Basically – anything that is not a letter or number.

How can I do this using RegEx?

Thanks so much!

Advertisement

Answer

This is a difficult problem to solve using regex as the nominal pattern of a $ followed by word characters will fail in many situations.

However PHP has a built-in PHP parser that you can call: token_get_all. You can use this to find all the tokens in some PHP code, then filter that based on whether the token is a variable name or not:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement