用于解析JSON的正则表达式

时间:2010-01-06 18:43:34

标签: php regex json

我需要帮助在PHP中为这个模式编写正则表达式:

[[{"type":"media","view_mode":"small","fid":"1","attributes":{"width":0,"height":0,"src":"http://localhost/x.png"}}]]

这是文本的一部分,我试图用其他东西替换它。

想要使用preg_replace_all(),但无法弄清楚模式是什么。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

由于您说您需要在普通字符串中标识这些JSON字符串,因此可以使用此模式:

'/\[\[.*?]]/s'

含义:

\[\[    # match two consecutive '['-s
.*?     # reluctantly match any character
]]      # match two consecutive ']'-s

由于s标记,正则表达式中的.也会匹配换行符。

演示:

$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);

将输出:

Array
(
    [0] => Array
        (
            [0] => [[{"type":"media","view_mode":"small",
    "fid":"1","attributes":{"width":0,"height":0,"src":
    "localhost/d7mw/sites/…;}}]]
        )

)

答案 1 :(得分:2)

这看起来像JSON编码数据,您可以使用json_decode干净地解析,然后再与json_encode放在一起。这里不需要正则表达式。