since json dosn't support comments I need my own function to clean my comments My comments are css style, like this
/*comment*/
i tryed the following
$json = preg_replace("/(\/\*.?\*\/)/", "", $json);
but no luck. thank's
since json dosn't support comments I need my own function to clean my comments My comments are css style, like this
/*comment*/
i tryed the following
$json = preg_replace("/(\/\*.?\*\/)/", "", $json);
but no luck. thank's
echo preg_replace("#/\*.*?\*/#s", "", $json);
Notable changes:
#
as the pattern delimiter. By doing this, I don't need to
escape forward slashes, making the regex prettier to read.s
flag, which makes the .
also match new line characters.Beware, this will destroy comments inside a json string. An example json object that will get clobbered
{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}
Use the following:
$json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
$json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors
This will erase comments, multi line comments and empty lines
EDIT: as some of the guys were saying in the comments, you can use:
$json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);
To remove only comments that are not found within strings.
$string = "some text /*comment goes here*/ some text again /*some comment again*/";
$string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
echo $string; // some textsome text again
The complete php code to remove both single and multi-line comments.
$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)
Here a site you can test the code: https://www.phpliveregex.com