【问题标题】:remove fake comments from json file从 json 文件中删除虚假评论
【发布时间】:2013-07-20 13:26:52
【问题描述】:

因为 json 不支持 cmets 我需要我自己的函数来清理我的 cmets 我的cmets是css风格的,像这样

/*comment*/

我尝试了以下

    $json = preg_replace("/(\/\*.?\*\/)/", "", $json);

但没有运气。 谢谢

【问题讨论】:

标签: php regex


【解决方案1】:

删除单行和多行 cmets 的完整 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)

这里有一个可以测试代码的网站:https://www.phpliveregex.com

To test the first code line fill in like this picture:

【讨论】:

    【解决方案2】:

    使用以下内容:

    $json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
    $json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors
    

    这将清除 cmets、多行 cmets 和空行

    编辑:正如一些人在 cmets 中所说,您可以使用:

     $json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);
    

    仅删除字符串中未找到的 cmets。

    【讨论】:

    • @YotamOmer: 嵌入在字符串中的 cmets 将被此方法剥离。
    【解决方案3】:
    echo preg_replace("#/\*.*?\*/#s", "", $json);
    

    显着变化:

    • 我使用# 作为模式分隔符。通过这样做,我不需要 转义正斜杠,使正则表达式更易读。
    • 我添加了 s 标志,这使得 . 也匹配换行符。

    注意,这会破坏 json 字符串中的 cmets。将被破坏的示例 json 对象

    {"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}
    

    【讨论】:

    • 而且也会损坏{"a":"b/*c","d":"e"/*f*/} ---> {"a":"b}
    【解决方案4】:
    $string = "some text /*comment goes here*/ some text again /*some comment again*/";
    $string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
    echo $string; // some textsome text again
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-18
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      相关资源
      最近更新 更多