Regex - Need to pull json between site source code for specific javascript variable

Viewed 42

I'm using php to get the source html of a url. Once I have that source, I'd like to use regex to pull out a specific javascript variable value.

For Example:

<script>
    let varOne.dataLayer['products'] = [
        {"prdocutId":1,"productName":"foo"},
        {"productId":2,"proudctName":"bar"}
    ];
    // Here's a comment
    let vartwo.dataLayer['foo'] = 'bar';
</script>

I've tried the following regex:

varOne.dataLayer\['products'\]\s?=\s?([^;]*)

This works, but only because there is no ";" in the products array anywhere. i.e. if the productName for productID 1 were to be something like "foo;but not bar" then the regex wouldn't work.

Is there a way to tell regex to pull the JSON object after "varOne.dataLayer['products'] = " so that I can confidently get the values of the array?

Here's a regex101 fiddle i've been playing with: https://regex101.com/r/EXgTW1/1

1 Answers

Regex would be tricky for this since you probably have no control over the variables or the JS formatting. If you can use a library like this one to turn the JS variables into PHP variables, it would be much less brittle.

Related