Bob M
Bob M

Reputation: 411

How do you use a PHP function to strip comments out of a file, stylesheet or javascript?

I have a large commented file ( /* css comment style */ ) which needs to be cleansed of comments and later to have blank lines and other unnecessary baggage removed. The trouble I am having is that when I pass the variable for the file into the function that it returns 0 bytes. The example:

<?php

function minify($data) {
  global $data;  
  $data = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $data); // CSS comments
  $data = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $data); 
  return ($data);
}

function minify2($data) {
  global $data;
  return ($data);
}

ob_start();
include ("$file");
$style = ob_get_clean(); // grabs the file contents into the $style variable - verified

/* FILE OPERATIONS */

# $style = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $style); // CSS comments; works SUCCESSFULLY if run inline

#$style = minify($style); // FAILS

$style = minify2($style); // FAILS

$fpi = fopen("out.css", "w");

fwrite($fpi, "$style");

?>

I verified that $style is not empty be echoing it to the screen. If I execute the regex expression inline as you see above (commented out) it works perfectly; executing it within the function is the problem. I also tried a really elemental experiment, minify2, which also fails to return #data. Is there something really simple that I am missing?

Edited addendum:

Rather than using ob_start and ob_get_clean to get the file into the variable I also used the following commenting out ob_start ...:

#$style = file_get_contents("$file");

#$style = include ("$file");

In all 3 cases the variable is good. If I run the regex inline:

$style = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $style); // CSS comments; works SUCCESSFULLY if run inline

it works and the output file is written. Only when I pass it through the function does it fail with 0 bytes.

Upvotes: 0

Views: 257

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33823

The minify function appears to work fine when called without the global and the output buffer references.

The source file used for the test was 983 lines long with several comments - this was reduced to a single ( very long ) line with no comments very quickly ( actually took between approx 0.002s and 0.005s over several tests )

<?php

    # Test file located in same directory as this PHP script
    $file=__DIR__ . '/test-source.css';
    $target=__DIR__ . '/test-output.css';

    
    function minify($data) { 
        $data = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $data);
        $data = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $data); 
        return $data;
    }
    
    $css=minify( file_get_contents( $file ) );
    file_put_contents( $target, $css );
?>

Upvotes: 2

Related Questions