// 去除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;
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询