1

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?

martin
  • 393
  • 1
  • 6
  • 21
  • Depends how you dmannage the output, but essentialy you would need ob_start (ex: http://stackoverflow.com/questions/4401949/whats-the-use-of-ob-start-in-php) – ka_lin Sep 23 '16 at 09:55

1 Answers1

0

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.

Community
  • 1
  • 1
Damaged Organic
  • 8,175
  • 6
  • 58
  • 84
  • Thanks Kid Binary, I'm only running on xampp, so I doubt if I can try to implement this just yet. – martin Sep 23 '16 at 15:46
  • There is a section about "Sandboxed LAMP Server", if that is your issue. Hovewever, if you using shared hosting (or similar restricted environment), I suppose the only remaining option is to strip comments with regex and handle the output with `ob_*` functions. – Damaged Organic Sep 24 '16 at 10:54
  • How do you do it with regex? – martin Sep 25 '16 at 11:51
  • Assuming I want to use regex, how do I parse the whole file and when? All the examples in your link seem to be parsing a variable. I want to eliminate //, /* and */ from within all the echo sections of the file? – martin Oct 03 '16 at 08:16
  • Load file to variable with `file_get_contents()` and work with it. Or your file is *that* large? – Damaged Organic Oct 03 '16 at 08:35
  • It's quite large. Feels like it would be a lot easier to re-write my file so that all comments are in php, it just means a lot of opening and closing of echo. Thanks for your feedback. – martin Oct 03 '16 at 17:56