Php 从json文件中删除假注释
由于json不支持注释,我需要自己的函数来清理注释 我的评论是css风格的,就像这样Php 从json文件中删除假注释,php,regex,Php,Regex,由于json不支持注释,我需要自己的函数来清理注释 我的评论是css风格的,就像这样 /*comment*/ 我尝试了以下方法 $json = preg_replace("/(\/\*.?\*\/)/", "", $json); 但是没有运气。 thank’s请使用以下命令: $json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments $json = preg_replace('/\n\s*\n/', "\n
/*comment*/
我尝试了以下方法
$json = preg_replace("/(\/\*.?\*\/)/", "", $json);
但是没有运气。
thank’s请使用以下命令:
$json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
$json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors
这将删除注释、多行注释和空行
编辑:正如一些人在评论中所说,您可以使用:
$json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);
$json=preg_replace('/\s*(?!$string=“一些文本/*注释放在这里*/一些文本/*一些注释*/”;
$string=preg_replace('/\s*(?)?!
显著变化:
- 我使用了
#
作为模式分隔符。这样做,我就不需要
避开前斜杠,使正则表达式更易于阅读
- 我添加了
s
标志,使
也匹配新行字符
注意,这将破坏json字符串中的注释
{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}
删除单行和多行注释的完整php代码
$json = preg_replace('!/\*.*?\*/!s', '', $json); //Strip multi-line comments: '/* comment */'
$json = preg_replace('!//.*!', '', $json); //Strip single-line comments: '// comment'
$json = preg_replace('/\n\s*\n/', "\n", $json); //Remove empty-lines (as clean up for above)
这里是一个可以测试代码的站点:
您的?
占位符只匹配一个任意字符,或者不匹配任何字符。这对于正则表达式来说是一个很高的要求,因为您需要处理“这是一个字符串/*这不是注释*/”之类的情况
其中不应删除/*
和*/
之间的内容。可能重复的@YotamOmer:string中嵌入的注释将使用此方法删除。
{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}
$json = preg_replace('!/\*.*?\*/!s', '', $json); //Strip multi-line comments: '/* comment */'
$json = preg_replace('!//.*!', '', $json); //Strip single-line comments: '// comment'
$json = preg_replace('/\n\s*\n/', "\n", $json); //Remove empty-lines (as clean up for above)