时间:2021-07-01 10:21:17 帮助过:91人阅读
$script='';
怎么把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}]这段截取出来?
请教一个正则截取问题
$script='';
怎么把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}]这段截取出来?
(?<="contacts"\:\[){.*}(?=\].*\.contacts)
注:PHP里好像需要把"转义一下变成\"
顺便推荐一个正则参考用的网址:http://deerchao.net/tutorials/regex/regex.htm
PHP的DEMO:
preg_match_all("/\[{.*?\}]/is", $script, $matches);
$result = json_decode($matches[0][1]);
这个正则不是最佳方案,不过结果是你想要的就是。
我觉得没必要把中间的截取出来,
------------------ update ------------------
preg_match_all("/(?<=contacts\":)\s*\[\s*\{(.*?)\]/", $script, $matches);
var_dump($matches);
结果:
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}]"
}
}
关于那个正则表达式你可以在这个网站中优化:
debuggex