PHP: Strip empty lines and comments from files in a directory recursively

April 6, 2011

In a recent project I needed to strip all the empty lines and comments from all the files in a directory and it’s sub directories. Being a PHP developer I naturally turned to PHP to do the work for me. What I came up with is a simple solution that let’s you send in a directory path as a parameter. That directory is then recursively searched (goes into all the directories). All the files found are opened, empty lines and comments are stripped, then the file is overwritten with the clean file. This is the only line of code you need:

strip_empty_lines_comments("path/to/your/files");

This works great for my purposes. If you are wanting to do the same you will need to download the attached PHP file as it contains the implementation of the functions needed to pull this off.

Download the PHP file with the required functions here

Take note that this opens EVERY file. In the future I might expand it to specific file extensions.

Questions, Comments? Leave them below

2 thoughts on “PHP: Strip empty lines and comments from files in a directory recursively

  1. marco (June 10, 2011)

    Hi,

    thank you! Helped me a lot. 🙂

    Found one bug:
    Double slash inside of a string is recognized as comment. That’s wrong. :-/
    Sample: echo ‘This is a string with an URL http://gapcode.com‘;

    Marco

  2. kevin (April 12, 2014)

    love you dude… you are awesome 🙂