2

I have some html code, which also includes a javascript tag and some json inside.

The json object looks like this:

var data =  {"service_notice":"111111-aa-bb-222222"}

I would like to extract the value for service_notice. How can this be done with regex?

I am also concerned that it could be formatted slightly differently:

var data =  {"service_notice" : "111111-aa-bb-222222"}

or

var data = {
    "service_notice" : 
        "111111-aa-bb-222222" }
3
  • Can you use json_decode php.net/manual/en/function.json-decode.php ? Commented May 24, 2013 at 18:34
  • No unfortunately i have the code as a string. It is included in an html string Commented May 24, 2013 at 18:34
  • preg_match('#\{.*?\}#s', $string, $m);print_r(json_decode($m[0])); Good day ... Commented May 24, 2013 at 18:38

1 Answer 1

2

You can use json_decode

 json_decode(substr($code, strpos($code, "{")-1, strpos($code, "}") - strpos($code, "{") + 2), true)

will yield an array that looks like

 array("service_notice"=>"111111-aa-bb-222222");

Thanks @HamZaDzCyberDeV

Sign up to request clarification or add additional context in comments.

2 Comments

This will obviously fail since he's parsing it from an html code, something like this should do the job: print_r(json_decode(substr($code, strpos($code, "{")-1, strpos($code, "}") - strpos($code, "{") + 2), true));
Nope, edit your answer and I'll upvote since it's your idea :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.