php 去除json中注释部分; json允许注释

180it 2021-11-05 PM 965℃ 0条
// 去除json中注释部分; json允许注释
// 支持 // 和 /*...*/注释 
function json_comment_clear($str){
    $result = '';
    $inComment = false;
    $commentType = '//';// /*,//
    $quoteCount  = 0;
    $str = str_replace(array('\"',"\r"),array("\\\0","\n"),$str);

    for ($i=0; $i < strlen($str); $i++) {
        $char = $str[$i];
        if($inComment){
            if($commentType == '//' && $char == "\n"){
                $result .= "\n";
                $inComment = false;
            }else if($commentType == '/*' && $char == '*' && $str[$i+1] == '/'){
                $i++;
                $inComment = false;
            }
        }else{
            if($str[$i] == '/'){
                if($quoteCount % 2 != 0){//成对匹配,则当前不在字符串内
                    $result .= $char;
                    continue;
                }    
                if($str[$i+1] == '*'){
                    $inComment = true;
                    $commentType = '/*';
                    $i++;
                    continue;
                }else if($str[$i+1] == '/'){
                    $inComment = true;
                    $commentType = '//';
                    $i++;
                    continue;
                }
            }else if($str[$i] == '"'){
                $quoteCount++;
            }
            $result .= $char;
        }
    }
    $result = str_replace("\\\0",'\"',$result);
    $result = str_replace("\n\n","\n",$result);
    return $result;
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 去除json中注释部分; json允许注释