Here's my attempt:
<?php
$json_origen = <<<'JSON'
{
//Remove this comment
"Command": "storeSystemConfig", /*1234*/
"SystemId": "1234", //Remove this comment
/*Remove this and the
empty line above and below*/
/*This can be removed but not what behind here =>*/ "TestParam": "Hello",
"TestString": "DNR this comment /*don not remove*/ and also this one: //Test comment" /*4321*/ //1234
}
JSON;
//Remove lines with only single line comments
$json = preg_replace("/[\n\r]\s*\/\/.*/", "", $json_origen);
//Remove all lines with only multi line comments
$json = preg_replace("/(?<=[\n\r])\s*\/\*(.[\n\r]?)*?\*\/\s*?/", "", $json);
//Remove lines multi line comments at the end
$json = preg_replace("/(\".+?(?<!\\\\)\"\s*,?)\s*\/\*(.[\n\r]?)*?\*\/\s*?/", "\\1", $json);
//Remove comment at the end of a line
$json = preg_replace("/(\".+?(?<!\\\\)\"\s*,?)\s*\/\/.*?(?=[\n\r])/", '\\1', $json);
//Remove empty lines
$json = preg_replace('/\n\s*\n/', "\n", $json);
echo($json);
?>
There's also the issue of multi line comments after a normal JSON statement but I have to write my uni exams now lol, I'll update this answer for it soon. For the sample input though, this should work.
Lemme know if there are any other extraneous situations that might occur in your JSON.
EDIT 1: Solved a possible problem where a value could contain double quotes, using the negative lookbehind (?<!\\\\)
, so escaped double quotes don't count
EDIT 2: Fixed the multi-line-comment-after-normal-json-statements problem I talked about.
EDIT 3: I provided the answer but not the detailed solution, so the concepts I used here are positive and negative lookbehinds and lookaheads. Also I have a habit of using [\n\r]
instead of just \n
because other problems might occur lol
EDIT 4: There was an issue where a single line comment after a multi line comment is not removed if they're both in the same line. Fixed that by simply changing the order of regex removals.
EDIT 5: Fixed the multi-line comment after json statement issue, just needed to check for a possible comma after the statement