PHP解碼JSON并清除多余字符串的超強(qiáng)函數(shù)json_clean_decode()

2015-07-31 16:04:20來源:威易網(wǎng)作者:icech

PHP提供了對JSON格式字符串的編碼和解碼的函數(shù),分別為json_encode()和json_decode(),但是其實(shí)在JSON字符串中會(huì)有非常多的“臟字符串”,比如換行符、轉(zhuǎn)移符什么的。

PHP提供了對JSON格式字符串的編碼和解碼的函數(shù),分別為json_encode()和json_decode(),但是其實(shí)在JSON字符串中會(huì)有非常多的“臟字符串”,比如換行符、轉(zhuǎn)移符什么的。

下面就介紹一個(gè)能夠清理這些無用字符串的界面函數(shù),功能是和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官方。
關(guān)鍵詞:PHPJSON函數(shù)