Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing comments from JS / CSS file using [PHP]

Tags:

css

php

minify

I'm building a PHP script to minify CSS/Javascript, which (obviously) involves getting rid of comments from the file. Any ideas how to do this? (Preferably, I need to get rid of /**/ and // comments)

like image 958
Jamie McElwain Avatar asked Dec 22 '10 15:12

Jamie McElwain


4 Answers

Pattern for remove comments in JS

$pattern = '/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/';

Pattern for remove comments in CSS

$pattern = '!/\*[^*]*\*+([^/][^*]*\*+)*/!'; 

$str = preg_replace($pattern, '', $str);

I hope above should help someone..

REFF : http://castlesblog.com/2010/august/14/php-javascript-css-minification

like image 156
Dilip Rajkumar Avatar answered Oct 10 '22 01:10

Dilip Rajkumar


That wheel has been invented -- https://github.com/mrclay/minify.

like image 27
James Sumners Avatar answered Oct 10 '22 02:10

James Sumners


Take a look at minify, a "heavy regex-based removal of whitespace, unnecessary comments and tokens."

like image 30
schellack Avatar answered Oct 10 '22 03:10

schellack


Without preg patterns, without anything alike, this can be easily done with PHP built-in TOKENIZER. All three (PHP, JS and CSS as well) share the same way of representing comments in source files, and PHP's native, built-in token_get_all() function (without TOKEN_PARSE flag) can do dirty trick, even if the input string isn't well formed PHP code, which is exactly what one might need in this scenario. All it asks is <?php at start of the string and magic happens. :)

function no_comments ($tokens)
{   // Remove all block and line comments in css/js files with PHP tokenizer.
    $remove = [];
    $suspects = ['T_COMMENT', 'T_DOC_COMMENT'];
    $iterate = token_get_all ('<?php '. PHP_EOL . $tokens);

    foreach ($iterate as $token) 
    {
        if (is_array ($token)) 
        {
            $name = token_name ($token[0]); 
            $chr = substr($token[1],0,1);

            if (in_array ($name, $suspects) 
            && $chr !== '#') $remove[] = $token[1];
        }
    }

    return str_replace ($remove, null, $tokens);
}

The usage goes something like this:

echo no_comments ($myCSSorJsStringWithComments);
like image 25
Spooky Avatar answered Oct 10 '22 03:10

Spooky