$re = '/(
"(?:\\\\"|[^"])*?" (?# First try to match balanced quotes)
)
| (?# If not successfull, try the following -> find comments)
(
\/\*(?:.|\s)*?\*\/ (?# Match a block comment)
|
\/\/.* (?# Match a line comment)
)/mx';
$str = '// Regex to parse json with comments (see json 5)
{
"foo": {
"abc": [ // inline comment
123,
"multi /*", /*
block comment */
"*/ single //", // some comment // /* /* " */
"escaped \\" //",
456 // another inline comment "with quotes" "
],
"abc": {
"urls": ["https://www.google.com/a/b/cdeFGH", "https://www.google.com/a/b/cdeFGH"]
}
},
/*
Block comment in the middle
" "
*/
"bar": 999 // one more inline comment
}
// playground...
\\/\\*(\\*(?!\\/)|[^*])*\\*\\/|\\/\\/.*
\\/\\*(.|\\s)*?\\*\\/|\\/\\/.*
\\/\\*.*?\\*\\/|\\/\\/.*?$
*/
"[^"]+"|(\\S+)
"(?:[^"]|\\\\")+(?<!\\\\)"|(\\S+)
"(?:\\\\"|[^"])+"|(\\S+)
"(?:\\\\"|[^"])+"|(\\/\\*(.|\\s)*?\\*\\/|\\/\\/.*)
(?=(?:[^"]*"[^"]*")*[^"]*$)';
$subst = "$1";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php