Regex to strip comments and multi-line comments and empty lines

Ahmad Fouad picture Ahmad Fouad · Mar 13, 2009 · Viewed 38k times · Source

I want to parse a file and I want to use php and regex to strip:

  • blank or empty lines
  • single line comments
  • multi line comments

basically I want to remove any line containing

/* text */ 

or multi line comments

/***
some
text
*****/

If possible, another regex to check if the line is empty (Remove blank lines)

Is that possible? can somebody post to me a regex that does just that?

Thanks a lot.

Answer

chaos picture chaos · Mar 13, 2009
$text = preg_replace('!/\*.*?\*/!s', '', $text);
$text = preg_replace('/\n\s*\n/', "\n", $text);