-4

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?

17
  • You'll have to use AJAX to pass the data to PHP. Commented Feb 12, 2016 at 19:32
  • @BrianRay: I think you misunderstood the question. An HTTP layer doesn't appear to be involved here at all. The OP has a string which contains JavaScript code, and wants to parse the syntax of that string into a structure. Commented Feb 12, 2016 at 19:33
  • what is your goal? javascript is client-side, php server-side: there are not interaction. You want extract javascript variables from html code? Commented Feb 12, 2016 at 19:34
  • @fusion3k My goal: get all js variables from javascript string and parse it to php array Commented Feb 12, 2016 at 19:35
  • 2
    @SzymonMarczak: Why exactly are you sending JavaScript language to the server to be parsed? What are you intending to accomplish here? Commented Feb 12, 2016 at 19:43

1 Answer 1

2

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

This is really nice! Thank You! Please remember that the var may not be used to set the variable... Anyway, good job!
I did a mistake. It works very well! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.