views:

2805

answers:

4

Hello,

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.

+5  A: 
$text = preg_replace('!/\*.*?\*/!s', '', $text);
$text = preg_replace('/\n\s*\n/', "\n", $text);
chaos
Thanks a lot! The first regex removed single line comments. However the second regex did no change and didn't remove multi line comments. I appreciate your response..thanks again
Ahmad Fouad
Make sure you have the !s on the first regex; it wasn't in my initial answer. That's what makes it handle multiline comments. The second pattern removes empty lines.
chaos
The !s makes it work 100%. It works much better than my regex, +1 from me.
St. John Johnson
+2  A: 

Keep in mind that any regex you use will fail if the file you're parsing has a string containing something that matches these conditions. For example, it would turn this:

print "/* a comment */";

Into this:

print "";

Which is probably not what you want. But maybe it is, I don't know. Anyway, regexes technically can't parse data in a manner to avoid that problem. I say technically because modern PCRE regexes have tacked on a number of hacks to make them both capable of doing this and, more importantly, no longer regular expressions, but whatever. If you want to avoid stripping these things inside quotes or in other situations, there is no substitute for a full-blown parser (albeit it can still be pretty simple).

Chris Lutz
+2  A: 

It is possible, but I wouldn't do it. You need to parse the whole php file to make sure that you're not removing any necessary whitespace (strings, whitespace beween keywords/identifiers (publicfuntiondoStuff()), etc). Better use the tokenizer extension of PHP.

soulmerge
I want to count on regex only. The file is too simple, it has couple of single line comments, multi line comment, and some PHP codes (each in a new line) .. i just want a regex formula that makes a clean-up...so i can use the output in the browser for different use.
Ahmad Fouad
A: 

This should work in replacing all /* to */.

$string = preg_replace('/(\s+)\/\*([^\/]*)\*\/(\s+)/s', "\n", $string);
St. John Johnson
Appreciate your help as well. Thank you!
Ahmad Fouad