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:

$isTrue ? $a : $b
or
$a=$b * ($c + 1)

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!

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:

function get_variables($code) {
    // get all the tokens
    $tokens = token_get_all("<?php $code ?>");
    // filter out non-variables
    $tokens = array_filter($tokens, function ($t) { return $t[0] == T_VARIABLE; });
    // return the variable names
    return array_column($tokens, 1);
}

print_r(get_variables('$isTrue ? $a : $b'));
print_r(get_variables('$a=$b * ($c + 1)'));

Output:

(
    [0] => $isTrue
    [1] => $a
    [2] => $b
)
Array
(
    [0] => $a
    [1] => $b
    [2] => $c
)

Demo on 3v4l.org