首页 > 后端开发 > php教程 > php正则匹配截取json

php正则匹配截取json

WBOY
发布: 2016-06-06 20:49:16
原创
2606 人浏览过

请教一个正则截取问题

<code class="lang-php">
$script='<script type="text/javascript">
cgiData={
pageIdx : 0,
pageCount : 1,
pageSize : 100,
groupsList : ({"groups":[{"id":0,"name":"未分组","cnt":16},{"id":1,"name":"黑名单","cnt":0},{"id":2,"name":"星标组","cnt":0}]}).groups,
        friendsList : ({"contacts":[{"id":6,"nick_name":"yan","remark_name":"","group_id":0},{"id":8,"nick_name":"mm","remark_name":"","group_id":0},{"id":4,"nick_name":"gg","remark_name":"","group_id":0},{"id":2,"nick_name":"sa","remark_name":"","group_id":0}]}).contacts,
            currentGroupId : 0,
        type : 0,
    userRole : 1 * 1,
    verifyMsgCount :  * 1
};
seajs.use("user/index");
</script>';

</code>
登录后复制
登录后复制

怎么把contacts中间的[{"id":6,"nickname":"yan","remarkname":"","groupid":0},{"id":8,"nickname":"mm","remarkname":"","groupid":0},{"id":4,"nickname":"gg","remarkname":"","groupid":0},{"id":2,"nickname":"sa","remarkname":"","groupid":0}]这段截取出来?

回复内容:

请教一个正则截取问题

<code class="lang-php">
$script='<script type="text/javascript">
cgiData={
pageIdx : 0,
pageCount : 1,
pageSize : 100,
groupsList : ({"groups":[{"id":0,"name":"未分组","cnt":16},{"id":1,"name":"黑名单","cnt":0},{"id":2,"name":"星标组","cnt":0}]}).groups,
        friendsList : ({"contacts":[{"id":6,"nick_name":"yan","remark_name":"","group_id":0},{"id":8,"nick_name":"mm","remark_name":"","group_id":0},{"id":4,"nick_name":"gg","remark_name":"","group_id":0},{"id":2,"nick_name":"sa","remark_name":"","group_id":0}]}).contacts,
            currentGroupId : 0,
        type : 0,
    userRole : 1 * 1,
    verifyMsgCount :  * 1
};
seajs.use("user/index");
</script>';

</code>
登录后复制
登录后复制

怎么把contacts中间的[{"id":6,"nickname":"yan","remarkname":"","groupid":0},{"id":8,"nickname":"mm","remarkname":"","groupid":0},{"id":4,"nickname":"gg","remarkname":"","groupid":0},{"id":2,"nickname":"sa","remarkname":"","groupid":0}]这段截取出来?

(?

注:PHP里好像需要把"转义一下变成\"
顺便推荐一个正则参考用的网址:http://deerchao.net/tutorials/regex/regex.htm

PHP的DEMO:

<code>preg_match_all("/\[{.*?\}]/is", $script, $matches);
$result = json_decode($matches[0][1]);
</code>
登录后复制

这个正则不是最佳方案,不过结果是你想要的就是。

我觉得没必要把中间的截取出来,

  • 很简单的就可以把前后两个script剥离
  • json_encode剩下的字符串
  • 访问你需要的值

------------------ update ------------------

<code class="lang-php">preg_match_all("/(?</code>
登录后复制

结果:

<code>array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(226) "[{"id":6,"nick_name":"yan","remark_name":"","group_id":0},{"id":8,"nick_name":"mm","remark_name":"","group_id":0},{"id":4,"nick_name":"gg","remark_name":"","group_id":0},{"id":2,"nick_name":"sa","remark_name":"","group_id":0}]"
  }
}
</code>
登录后复制

关于那个正则表达式你可以在这个网站中优化:
debuggex

相关标签:
php
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板