0

I'm looking for regex to extract json string from text. I have the text below, which contains. My json:

[
  {
    "message": "(.*)",
    "answer": " :с"
  },
  {
    "message": "http:\/\/(.*)\.(.*)\/[\S\s]+\ ?",
    "answer": "No!"
  }
]

And php parse:

json_decode($json); //null
var_dump(json_last_error() == JSON_ERROR_SYNTAX); //true
4
  • Where are you stuck in specific? Commented Feb 1, 2016 at 19:51
  • Just to make sure: PHP has some beautifully crafted JSON functions build in already - trying to do everything with regular expressions shows a lack of phantasy :-) Commented Feb 1, 2016 at 19:56
  • @Jan his issue is an invalid JSON input actually ;-) Commented Feb 1, 2016 at 20:06
  • @LucasTrzesniewski: ...ouch... ;-) Commented Feb 1, 2016 at 20:20

1 Answer 1

1

If you call json_last_error_msg() you'll get the following:

invalid string sequence

Indeed, the string "http:\/\/(.*)\.(.*)\/[\S\s]+\ ?" is not a valid JSON string per the spec:

JSON string spec
(source: json.org)

Your string contains invalid escapes, such as \S, \., \s and (space).

Instead, try to escape each backslash:

$str = <<<'END'
[
  {
    "message": "(.*)",
    "answer": " :с"
  },
  {
    "message": "http:\\/\\/(.*)\\.(.*)\\/[\\S\\s]+\\ ?",
    "answer": "No!"
  }
]
END;

$json = json_decode($str);
var_dump($json);

This works.

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

Comments

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.