简体   繁体   中英

Removing comments from a group of php files via command line in Windows

I have a bunch of files and I would like to send them to deployment sans any comments but with whitespace intact (so that I can make any quick changes in production in emergency cases).

The comments can be either single line comments ( # , // ) or multi line syntax /**/ and at any indentation level.

I want to create a batch file that when executed from any directory reads all php files and strips their comments.

I am not even sure what to try. I know I can fetch all the files with .php extension easily and loop through them. Replacing their content is easy enough as well. What I am stuck on is how to remove the comments.

There's multiple ways to do it, but I think the most efficient will be to use regular expressions. I'm not a RegExp guru, but I know that you can use grep (or any powerfull text editor such as Notepad++, sublimetext, et...) to replace expressions highlighted to empty string.

For example, in Sublime Text, I've tested this regular expression, which find any multiple lines comment :

\/\*([\s\S]*?)\*/|//.*|#.*

Quick Explanation :

  • the regexp is made of 3, with an OR symbol inside ( the pipe symbol | )
  • the first expression mean "something starting with /*, any character, or any blank character , and finishing with */"
  • the second means "any expression starting with // and any character following
  • the third means "any expression starting with # and any character following

Once you've set this search expression in sublime text, you can replace what it did return with a "blank" replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM