1

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

dj_boy
  • 103
  • 1
  • 3
  • 9
  • Your `.?` placeholders just matches one arbitrary character, or no character. – mario Jul 21 '13 at 21:12
  • 2
    Thats a pretty tall order for regex since you'll need to handle cases like `"this is a string /*this is not a comment*/"` where things between `/*` and `*/` shouldn't be removed. – go-oleg Jul 21 '13 at 21:12
  • possible duplicate of [Regular expression to remove CSS comments](http://stackoverflow.com/questions/3984380/regular-expression-to-remove-css-comments) – mario Jul 21 '13 at 21:13
  • possible duplicate of [Regex to strip comments and multi-line comments and empty lines](http://stackoverflow.com/q/643113) – mario Jul 21 '13 at 21:15

4 Answers4

4
echo preg_replace("#/\*.*?\*/#s", "", $json);

Notable changes:

  • I used # as the pattern delimiter. By doing this, I don't need to escape forward slashes, making the regex prettier to read.
  • I added the 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******/"}
goat
  • 31,486
  • 7
  • 73
  • 96
2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
2
$string = "some text /*comment goes here*/ some text again /*some comment again*/";
$string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
echo $string; // some textsome text again
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

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

To test the first code line fill in like this picture:

Micket
  • 17
  • 2