我正在尝试读取php文件,以便提取它们的所有变量并将它们存储在一个对象中。然后,我想得到变量的值,并将它添加到对象中。如果变量位于未知文件中,如何获得它的值?
解析文件的代码:
function scan($file){
$vars = (object) array();
$tokens = token_get_all(file_get_contents($file));
foreach($tokens as $token){
if ($token[0] == 312){ //if the token is a variable
$vars->{substr($token[1], 1)} = VALUE OF CURRENT TOKEN ;
}
}
return $vars;
}需要解析的代码:
<?php
$duck = "cow";
$lizard = "cat";
?>我希望返回的对象:
{
duck: "cow",
lizard: "cat"
}发布于 2017-03-24 22:01:27
这是个可怕的任务。只有预科才能帮你。就像这样:
<?php
$filetext = '
<?php
$duck = "cow";
$lizard = "cat";
$qwert = 4;
$asdfg=2;
?>
';
preg_match_all('/\$(\w+)\s*=\s*(\S+);/', $a, $matches);
var_dump($matches);
if (!empty($matches[1])) {
$object = new stdClass();
foreach($matches[1] as $key => $value) {
$object->{$value} = trim($matches[2][$key], '\'"');
}
}
var_dump($object);https://stackoverflow.com/questions/43008937
复制相似问题