Alex Rivera | Logout

Best way to automatically remove comments from PHP code

Asked 2009-02-02T16:48:00.560
57

What’s the best way to remove comments from a PHP file?

I want to do something similar to strip-whitespace() - but it shouldn't remove the line breaks as well.

For example,

I want this:

<?PHP
// something
if ($whatsit) {
    do_something(); # we do something here
    echo '<html>Some embedded HTML</html>';
}
/* another long
comment
*/
some_more_code();
?>

to become:

<?PHP
if ($whatsit) {
    do_something();
    echo '<html>Some embedded HTML</html>';
}
some_more_code();
?>

(Although if the empty lines remain where comments are removed, that wouldn't be OK.)

It may not be possible, because of the requirement to preserve embedded HTML - that’s what’s tripped up the things that have come up on Google.

Edit
Report

2 Answers

49

Use php -w <sourcefile> to generate a file stripped of comments and whitespace, and then use a beautifier like PHP_Beautifier to reformat for readability.

answered 2009-02-02T17:02:22.247
10
$fileStr = file_get_contents('file.php');
foreach (token_get_all($fileStr) as $token ) {
    if ($token[0] != T_COMMENT) {
        continue;
    }
    $fileStr = str_replace($token[1], '', $fileStr);
}

echo $fileStr;
answered 2009-02-02T17:06:17.467

Your Answer