解析JavaScript变量声明

希蒙·马尔恰克(Szymon Marczak)

这里有什么方法可以解析PHP中的JavaScript语法吗?

我想在PHP数组中获取所有JS变量

$string = 'var variable = "hello";
           var thisIsVariableToo = "world";
           var and = ["this", "is"];
           var its = new Array("amazing");
           var nice = null;';

我想从该(^^^)字符串中获取PHP:

$string = [
    "variable" => "hello",
    "thisIsVariableToo" => "world",
    "and" => ["this", "is"],
    "its" => ["amazing"],
    "nice" => null
]

我该怎么做?

莫沃里塞克

那这个呢?

$str = 'var variable = "hello";
var thisIsVariableToo = "world";
var and = ["this", "is"];
var its = new Array("amazing");
var nice = null;';

preg_match_all('~^var\s+([^=]+?)\s*=\s*(.+?)\s*;?\s*$~imu', $str, $matchesAll, PREG_SET_ORDER);
$arr = array();
foreach ($matchesAll as $matches) {
    $arr[$matches[1]] = $matches[2];
}

print_r($arr);

输出以下内容:

Array
(
    [variable] => "hello"
    [thisIsVariableToo] => "world"
    [and] => ["this", "is"]
    [its] => new Array("amazing")
    [nice] => null
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章