Reputation: 1005
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
Upvotes: 2
Views: 3907
Reputation: 1982
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]);
Upvotes: 7
Reputation:
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]);
// --------------
Upvotes: 1
Reputation: 145482
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.
Upvotes: 5