phpstringvariablestext-extraction

Get all substrings that look like PHP variable names


Let's say I have a string My name is $name and my pet is $animal.

How can I check if the string has variables inside it? And if has, add them to an array like"

$array = ['$name', '$animal'];

Would it be some pregmatch()? ...but then all $+sometextafterthesymbol needs to be extracted and `$° with a space after it left alone. Any ideas?


Solution

  • You can use regular expressions for this. The following will match any dollar sign followed by 1 or more word characters (letters, numbers, or underscore):

    preg_match_all('/\$(\w+)/', $string, $matches);
    

    $matches:

    Array
    (
        [0] => Array
            (
                [0] => $name
                [1] => $animal
            )
    
        [1] => Array
            (
                [0] => name
                [1] => animal
            )
    
    )
    

    Remember that $string, if hardcoded, must be wrapped in single quotes (').