Click Upvote Click Upvote - 6 months ago 24
PHP Question

Easiest way to remove all whitespace from a code file?

So I'm participating in one of the Code Golf competitions where the smaller your file size is, the better.

Rather than manually removing all whitespace etc, I'm looking for a program or website which will take a file, remove all whitespace (including new lines) and return a compact version of the file. any ideas?

Answer

you could use

sed 's/\s\s+/ /g' youfile > yourpackedfile

there is also this online tool

you can even do it in PHP (how marvelous is life)

$data = file_get_contents('foobar.php');
$data = preg_replace('/\s\s+/', ' ', $data);
file_put_contents('foobar2.php',$data);

You have to note this won't take care of string variable like $bar = ' asd aa a'; it might be a problem depends on what you are doing. The online tool seems to handle this properly.