删除php文件中的javascript注释

I have a javascript file, myjs.php, that is generated on the server and delivered to the browser with a header.

Header("content-type: application/x-javascript; charset=utf-8");

The file is large and contains a lot of comments that are echoed within the js sections:

echo "  // comments   /* comments */ etc.

I appreciate that, if necessary, I could rewrite the php so that all comments were within php sections.

Is there a way, within PHP, to remove these comments at runtime so that they are not part of the file that is delivered to the browser, either by minifying or by some other means?

You can use tool such as UglifyJS from a PHP wrapper. There are packages to handle it, like UglifyPHP. After your file is generated, run the minifier on it, which will also strip comments:

use UglifyPHP\JS;

$js = new JS(['myjs.php']);

$js->minify('myjs.js', [
    'comments' => false,
]);

In combination with ob_start(), ob_get_contents(), ob_end_clean() and using raw file stream as input you can achieve desired result.


Update:

Added this on demand by OP, if one haven't got possibility to use anything other than pure LAMP stack.

Here's a reference on how to remove single- and multiline PHP comments from a file:

Regex to strip comments and multi-line comments and empty lines

And here's working universal solution:

Best way to automatically remove comments from PHP code

This do the trick.