从 JSON 数据中删除注释

Des*_*ume 2 php regex json comments

我需要/*...*/从 JSON 数据中删除所有样式注释。我如何使用正则表达式来实现这样的字符串值

{
    "propName": "Hello \" /* hi */ there."
}
Run Code Online (Sandbox Code Playgroud)

保持不变?

Cas*_*yte 5

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

$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);
Run Code Online (Sandbox Code Playgroud)

图案详情:

"(?:[^\\\"]+|\\\.)*+"
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

/\*(?:[^*]+|\*+(?!/))*+\*/
Run Code Online (Sandbox Code Playgroud)

这部分描述了评论中的内容。

/\*           # 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
Run Code Online (Sandbox Code Playgroud)

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