Search code examples
javascriptphpregexpreg-match

I am having trouble extracting a value from Javascript with PHP


I received the below code amongst a whole lot of HTML from a fetch in php, the code was in script tags. I am having trouble using preg_match efficiently to extract the value of hardest27 on a certain line.

So I currently have a variable called $html that contains a whole lot of HTML which also contains the line below.

$("<input>").attr({name: "levelReached", value: "hardest27" }).appendTo(newForm);

How can I get php to return me the value of levelReached?


Solution

  • You may try this regex over the content:

    "levelReached"\s*,\s*value:\s*"([^"]*)"
    

    group 1 contains your expected value.

    Regex Demo

    Sample Demo Source:

    preg_match_all($re, $html, $matches);
    
    foreach($matches[1] as $matchgroup)
        echo $matchgroup."\n";