Removing blank spaces before and after PHP tags – Part II

Last month I posted a PHP script to find all the blank spaces before and after PHP opening (<?php ) and closing tag ( ?>). The script works nicely, but it only identifies files having blank spaces or lines before or after PHP tag. It does not remove them.

Luckily, I came across a google group discussion in which Chris Lamb posted a single line statement (magic command) to get rid of all the trailing spaces before the PHP tag. For the sake of completeness, I emailed Chris, asking him whether he will be willing to share the second magic command – statement to remove all the leading spaces. And he was kind enough to email me the other part of the solution. Below are his magic commands:

 1. Command to remove all the trailing spaces
$ find -name “*.php” | xargs sed -i -e :a -e ‘/^\n*$/{$d;N;ba’ -e ‘}’

2. Command to remove all the leading spaces
$ find -name “*.php” -exec sed -i -e :a -e N -e ‘s/\s*//’ {} \;

The cache is these commands work only unix/linux box. But don’t worry if you happen to have a windows machine. To get them working on windows, you will need to download Cygwin. Cygwin is an excellent linux emulator for windows. Once you installed cygwin, follow these steps:

1. Navigate to your directory which contains all your PHP files. Below is the sample statement on how to navigate to your directory
$ cd c:/folder1/subfolder1/htdocs/mysite/app/models

2. Use “pwd” command to echo the current directory. This is just to make sure that you are in right place
$ pwd    

3. Now use the above magic commands to remove leading and trailing blank spaces from your PHP files

That’s all



6 thoughts on “Removing blank spaces before and after PHP tags – Part II

  1. hi Richard,

    you are right. But personally, I won’t advise that. To me, removing the closing tag introduces ambiguity as determining whether the code (especially for others) is incomplete or is meant to be like that.

  2. Hi,

    I have an error executing this:

    find -name “*.php” | xargs sed -i -e :a -e ‘/^\n*$/{$d;N;ba’ -e ‘}’
    sed: -e expression #2, char 1: unknown command: `‘’
    -bash: N: command not found
    -bash: ba’: command not found

  3. I can’t thank you enough for this trick. I’ve spent hours and hours trying to fix a blank space before a doctype declaration on a wordpress template and your command just did what had to be done. Awesome tip.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s