PHP解码JSON并清除多余字符串的超强函数json_clean_decode()
PHP提供了对JSON格式字符串的编码和解码的函数,分别为json_encode()和json_decode(),但是其实在JSON字符串中会有非常多的“脏字符串”,比如换行符、转移符什么的。
下面就介绍一个能够清理这些无用字符串的界面函数,功能是和json_decode()一样,但是效果却不同哦:
1 <?php 2 function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) { 3 // search and remove comments like /* */ and // 4 $json = preg_replace("#(/*([^*]|[ ]|(*+([^*/]|[ ])))**+/)|([s ]//.*)|(^//.*)#", ’’, $json); 5 6 if(version_compare(phpversion(), ’5.4.0’, ’>=’)) { 7 $json = json_decode($json, $assoc, $depth, $options); 8 } 9 elseif(version_compare(phpversion(), ’5.3.0’, ’>=’)) { 10 $json = json_decode($json, $assoc, $depth); 11 } 12 else { 13 $json = json_decode($json, $assoc); 14 } 15 16 return $json; 17 } 18 ?>
代码来自于PHP官方。