Is here any way to parse JavaScript syntax in PHP?
I want to get all JS variables in PHP array
$string = 'var variable = "hello";
var thisIsVariableToo = "world";
var and = ["this", "is"];
var its = new Array("amazing");
var nice = null;';
I want to get in PHP from that (^^^) string:
$string = [
"variable" => "hello",
"thisIsVariableToo" => "world",
"and" => ["this", "is"],
"its" => ["amazing"],
"nice" => null
]
How I can do that?
答案 0 :(得分:1)
What about this?
$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);
Which outputs this:
Array
(
[variable] => "hello"
[thisIsVariableToo] => "world"
[and] => ["this", "is"]
[its] => new Array("amazing")
[nice] => null
)