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

By , April 6, 2011 10:55 am

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:

  1. 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

Leave a Reply

2 Responses to“ PHP: Strip empty lines and comments from files in a directory recursively”

  1. marco says:

    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 says:

    love you dude… you are awesome :)

Theme by Blam Designs
Based on Themocracy

Add this ribbon to your WordPress website re-abolish slavery
%d bloggers like this: