2

I'm looking for a PHP regular expression to match a pattern for multiple set of json data in a text string.

Paragraph One text

[[{"fid":"28","view_mode":"teaser","fields":{},"type":"media","attributes":{"class":"media-element file-teaser"},"link_text":null}]]

Second Paragraph

[[{"fid":"26","view_mode":"preview","fields":{},"type":"media","attributes":{"class":"file media-element file-preview"},"link_text":"mohan sample.mp4"}]]

Above is the example text with json samples, i want to extract the value of "fid" from each json data.

Any suggestions?

3
  • 1
    Wouldn't it be easier to json_decode() this and read the value directly? Commented Jan 23, 2015 at 6:54
  • @anubhava json_decode() won't work if it's mixed in with other text. He needs the regexp to find just the single JSON object so he can decode it. Commented Jan 23, 2015 at 6:56
  • Do you need to be able to match ANY JSON, or just something very similar to what you've posted? I suspect there's no easy regexp to match JSON in general, because of the recursion and escaping. Commented Jan 23, 2015 at 6:58

1 Answer 1

1
\[\[{(?:(?!\]\])[\s\S])*"fid":"\K\d+

You can try this.See demo.

https://www.regex101.com/r/rG7gX4/10

$re = "/\\[\\[{(?:(?!\\]\\])[\\s\\S])*\"fid\":\"\\K\\d+/mi";
$str = "[[{\"fid\":\"28\",\"view_mode\":\"teaser\",\"fields\":{},\"type\":\"media\",\"attributes\":{\"class\":\"media-element file-teaser\"},\"link_text\":null}]]\n\nSecond Paragraph\n\n[[{\"fid\":\"26\",\"view_mode\":\"preview\",\"fields\":{},\"type\":\"media\",\"attributes\":{\"class\":\"file media-element file-preview\"},\"link_text\":\"mohan sample.mp4\"}]]";

preg_match_all($re, $str, $matches);
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.