Back To Normal
Click Here To Subscribe Via Email

Subscribe To Our E-Mail Newsletter

Friday, August 22, 2014

PHP Function for CSS minification


Couch ModePrint It


Your website must have good page-load time. Unminified files (css, javascript etc) consumes a significant amount of page-load time. Hence, all files should be minified. Here I am sharing CSS minification function to use in PHP projects.
PHP code:
function minify_css($css){
/* remove comments */
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
/* remove tabs, spaces, newlines, etc. */
$css = str_replace(array("\r\n","\r","\n","\t",'  ','    ','     '), '', $css);
/* remove other spaces before/after ; */
$css = preg_replace(array('(( )+{)','({( )+)'), '{', $css);
$css = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $css);
$css = preg_replace(array('(;( )+)','(( )+;)'), ';', $css);
return $css;
}


Usage:

$css_input=<<<EOF
      div {
          margin:auto 1em;
      }
      #code {
          float:left;
          width:50%;
      }
      #html {
          float:right;
          width:50%;
      }
      #code2 {
          margin-right:1em;
      }
      #html2 {
          margin-left:1em;
      }
      #main textarea {
          width:100%;
          height:10em;
      }
      #html2 textarea {
          float:right;
      }
      #options {
          clear:both;
      }
      #divstyles {
          width:50%;
      }
      #preview {
          padding-bottom: 3em;
      }
      #footer {
          border-top:1px dotted #000;
      }
      #footer p {
          text-align:center;
          font-size:75%;
      }
EOF;
$css=minify_css($css_input);
echo "<style>$css</style>";


 You can see the live result here 

Don't forget to share your thoughts :)


:D
:)
:[
;)
:D
:O
(6)
(A)
:'(
:|
:o)
8)
(K)
(M)