How to list all PHP variables in a file?

▼魔方 西西 提交于 2020-01-11 04:16:28

问题


I have a PHP file with PHP Variables inside.
Example:

Hi <?=$username?>,
Can you please send me an email ?

I would like to list from an outside file, every PHP variables in this file.
Something that would return:

Array(
   'username'
);

I know there is a PHP function called get_defined_vars, but this is an external file.
Is there a way to get all PHP vars from an external file ?

Thank you


回答1:


Use file_get_contents() and preg_match_all():

$file = file_get_contents('file.php'); 
preg_match_all('/\$[A-Za-z0-9-_]+/', $file, $vars);

print_r($vars[0]);



回答2:


Depending on the expected accuracy a bit token_get_all() traversal will get you a list of variable basenames:

print_r(
    array_filter(
        token_get_all($php_file_content),
        function($t) { return $t[0] == T_VARIABLE; }
    )
);

Just filter out [1] from that array structure.

A bit less resilient, but sometimes still appropriate is a basic regex, which also allows to extract array variable or object syntax more easily.




回答3:


function extract_variables($content, $include_comments = false)
{
    $variables = [];

    if($include_comments)
    {
        preg_match_all('/\$[A-Za-z0-9_]+/', $content, $variables_);

        foreach($variables_[0] as $variable_)
            if(!in_array($variable_, $variables))
                $variables[] = $variable_;
    }
    else
    {
        $variables_ = array_filter
        (
            token_get_all($content),
            function($t) { return $t[0] == T_VARIABLE; }
        );

        foreach($variables_ as $variable_)
            if(!in_array($variable_[1], $variables))
                $variables[] = $variable_[1];
    }

    unset($variables_);
    return $variables;
}

// --------------

$content = file_get_contents("file.php");
$variables = extract_variables($content);

print_r($vars[0]);

// --------------


来源:https://stackoverflow.com/questions/8873094/how-to-list-all-php-variables-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!