用于解析JSON的正则表达式 [英] Regular expression to parse JSON

查看:202
本文介绍了用于解析JSON的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help with writing regular expression for this pattern in PHP:

[[{"type":"media","view_mode":"small","fid":"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.

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

Would like to use preg_replace_all() but can't figure out what would be the pattern. Any help appreciated.

推荐答案

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

Since you say you need to identify these JSON-strings inside a normal string, you could use this pattern:

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

含义:

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

由于s标志,正则表达式中的.也将匹配换行符.

Because of the s flag, the . in the regex will also match line breaks.

演示:

$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/…;}}]]
        )

)

这篇关于用于解析JSON的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆