从JSON数据中删除注释

时间:2013-11-11 15:31:19

标签: php regex json comments

我需要从JSON数据中删除所有/*...*/样式注释。如何使用正则表达式执行此操作,以便像这样的字符串值

{
    "propName": "Hello \" /* hi */ there."
}

保持不变?

1 个答案:

答案 0 :(得分:4)

您必须首先使用回溯控制动词跳过失败(或捕获)来避免使用双引号内的所有内容

$string = <<<'LOD'
{
    "propName": "Hello \" /* don't remove **/ there." /*this must be removed*/
}
LOD;

$result = preg_replace('~"(?:[^\\\"]+|\\\.)*+"(*SKIP)(*FAIL)|/\*(?:[^*]+|\*+(?!/))*+\*/~s', '',$string);

// The same with a capture:

$result = preg_replace('~("(?:[^\\\"]+|\\\.)*+")|/\*(?:[^*]+|\*+(?!/))*+\*/~s', '$1',$string);

模式详细信息:

"(?:[^\\\"]+|\\\.)*+"

这部分描述了引号内的可能内容:

"              # literal quote
(?:            # open a non-capturing group
    [^\\\"]+   # all characters that are not \ or "
  |            # OR
    \\\.)*+    # escaped char (that can be a quote)
"

然后,您可以使用(*SKIP)(*FAIL)(*SKIP)(?!)使此子模式失败。如果模式失败后, SKIP 禁止在此之前进行回溯。 FAIL 强制模式失败。因此,引用的部分被跳过(并且不能在结果中,因为您使子模式失败后)。

或者您使用捕获组并在替换模式中添加引用。

/\*(?:[^*]+|\*+(?!/))*+\*/

这部分描述了评论内容。

/\*           # open the comment
(?:           
    [^*]+     # all characters except *
  |           # OR
    \*+(?!/)  # * not followed by / (note that you can't use 
              # a possessive quantifier here)
)*+           # repeat the group zero or more times
\*/           # close the comment

仅当反斜杠位于引号内的换行符之前时,才使用s修饰符。

相关问题