开发者

Regular expression to parse JSON

开发者 https://www.devze.com 2022-12-15 20:05 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消