Regular expression to parse JSON
I need help with writing regular expression for this pattern in PHP:
[[{"type":"media","view_mode":"small","f开发者_运维技巧id":"1","attributes":{"width":0,"height":0,"src":"http://localhost/x.png"}}]]
This is part of the text and I am trying to replace this by something else.
Would like to use preg_replace_all()
but can't figure out what would be the pattern. Any help appreciated.
Since you say you need to identify these JSON-strings inside a normal string, you could use this pattern:
'/\[\[.*?]]/s'
meaning:
\[\[ # match two consecutive '['-s
.*? # reluctantly match any character
]] # match two consecutive ']'-s
Because of the s
flag, the .
in the regex will also match line breaks.
Demo:
$text = '<p>blahhah blahaa blahhah blahaablahhah blahaablahhah
blahaablahhah blahaablahhah blahaablahhah blahaablahhah
blahaablahhah blahaa [[{"type":"media","view_mode":"small",
"fid":"1","attributes":{"width":0,"height":0,"src":
"localhost/d7mw/sites/…;}}]] more blah more blah more blah
more blahmore blah more blahmore blah more blahmore blah
more blahmore blah more blahmore blah more blahmore blah
more blahmore blah more blahmore blah more blahmore blah
more blah</p>';
preg_match_all('/\[\[.*?]]/s', $text, $matches);
print_r($matches);
which will output:
Array
(
[0] => Array
(
[0] => [[{"type":"media","view_mode":"small",
"fid":"1","attributes":{"width":0,"height":0,"src":
"localhost/d7mw/sites/…;}}]]
)
)
This looks like JSON encoded data, which you can parse cleanly with json_decode, and put together again with json_encode. No need for regexes here.
精彩评论