Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What's the best way to strip all code comments in a given directory? I'd like to strip out all // ... EOL comments, and /* blah \*/ (or /** ... \*/) comments as well.

This is a PHP project, and I'd like to go a little further than what is outlined below, yet for security purposes rather than efficiency.

Any help would be greatly appreciated.

share|improve this question
1  
umm... how do you figure this is for security? removing comments will not enhance your security (unless you have a backdoor password in your comments, in which case nothing can help you) –  xenoterracide Oct 26 '10 at 22:21
    
@xenoterracide: The normal password would pose problem. Backdoor password might be deduced from code. –  Maciej Piechotka Oct 26 '10 at 22:36
    
I'm handing the code over to another party. It's a legal thing - that's all. –  Adrian Schneider Oct 26 '10 at 22:39

2 Answers 2

up vote 3 down vote accepted

A quick google search returns a similar question at stackoverflow.

share|improve this answer
    
Using PHP's tokenizer itself is probably the only safe way; any way involving perl/awk/whatever is going to have problems with things like $foo = "// you shouldn't be touching this!"; –  Michael Mrozek Oct 27 '10 at 10:50
    
Cool, will do some tests. Appears to be what I need though. Thanks –  Adrian Schneider Oct 28 '10 at 18:57

This will do it in Perl:

//will delete all comments starting at the beginning of the line with //
perl -p -i -e "s#^//.*$##" <your php file>
//will delete all comments starting somewhere in a line with //
perl -p -i -e "s#^(.*)//.*$#\$1#" <your php file>
//will delete all comments starting somewhere in a line with /* or /**
perl -p -i -e "s#^(.*)/\*+.*$#\$1#" <your php file>
//will delete all comments starting at the beginning of the line with /* or /**
perl -p -i -e "s#^/\*+.*$##" <your php file>

These commands will not delete comments with multiple lines, like

/**
 *
 *
 */

It is possible to do this, but multi line regex are way more difficult.

There will also be solutions for awk, sed, python, ... But this should also do it.

share|improve this answer
1  
Note that you are also going to have problems with strings that happen to have "//" inside them and likely other issues. –  Steven D Oct 27 '10 at 6:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.