PHP解码JSON并清除多余字符串的超强函数json

2015 年 8 月 20 日4410

PHP解码JSON并清除多余字符串的超强函数json_clean_decode()

PHP提供了对JSON格式字符串的编码和解码的函数,分别为json_encode()和json_decode(),但是其实在JSON字符串中会有非常多的“脏字符串”,比如换行符、转移符什么的。

PHP提供了对JSON格式字符串的编码和解码的函数,分别为json_encode()和json_decode(),但是其实在JSON字符串中会有非常多的“脏字符串”,比如换行符、转移符什么的。

下面就介绍一个能够清理这些无用字符串的界面函数,功能是和json_decode()一样,但是效果却不同哦:

<?php

function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {

// search and remove comments like /* */ and //

$json = preg_replace("#(/*([^*]|[

]|(*+([^*/]|[

])))**+/)|([s ]//.*)|(^//.*)#", ’’, $json);

if(version_compare(phpversion(), ’5.4.0’, ’>=’)) {

$json = json_decode($json, $assoc, $depth, $options);

}

elseif(version_compare(phpversion(), ’5.3.0’, ’>=’)) {

$json = json_decode($json, $assoc, $depth);

}

else {

$json = json_decode($json, $assoc);

}

return $json;

}

?>

代码来自于PHP官方。

关键词:

相关阅读:

赞助商链接:

0 0