How to list all PHP variables in a file?

后端 未结 3 1532
不知归路
不知归路 2021-01-07 11:53

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

Hi ,
Can you please send me an email ?

I would like to

相关标签:
3条回答
  • 2021-01-07 12:33

    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]);
    
    0 讨论(0)
  • 2021-01-07 12:34
    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]);
    
    // --------------
    
    0 讨论(0)
  • 2021-01-07 12:41

    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.

    0 讨论(0)
提交回复
热议问题