Posted By

thewickedchemist on 05/31/12


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

subhan
Johnb21


Run-time CSS Minifier


 / Published in: PHP
 

URL: http://www.lateralcode.com/css-minifier/

Usage is in the source, it is pretty self explanatory :)

  1. //Usage
  2. <link rel="stylesheet" type="text/css" href="minify.php?css=styles.css" />
  3.  
  4.  
  5. //minify.php
  6. <?php
  7. header( "Content-type: text/css" );
  8.  
  9. $file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
  10. if( !file || array_pop( split( '\.', $file ) ) != 'css' || strpos( $file, '/' ) !== false )
  11. die( 'Invalid Parameters' );
  12.  
  13. $content = @file_get_contents( $file );
  14. echo minify( $content );
  15.  
  16. function minify( $css ) {
  17. $css = preg_replace( '#\s+#', ' ', $css );
  18. $css = preg_replace( '#/\*.*?\*/#s', '', $css );
  19. $css = str_replace( '; ', ';', $css );
  20. $css = str_replace( ': ', ':', $css );
  21. $css = str_replace( ' {', '{', $css );
  22. $css = str_replace( '{ ', '{', $css );
  23. $css = str_replace( ', ', ',', $css );
  24. $css = str_replace( '} ', '}', $css );
  25. $css = str_replace( ';}', '}', $css );
  26.  
  27. return trim( $css );
  28. }
  29. ?>

Report this snippet  

You need to login to post a comment.