CSS or Cascading Style Sheets is a language used to describe the presentation of a document written in a markup language. If you're developing a very complex design for your site, CSS scripts become very long and take too much time to load. But a compressed CSS script can help your website load faster and easily maintain its functionality. Here, I’ve created a very simple CSS compressor using PHP to compress or reduce CSS script size.
The Simple CSS Compressor
Please click the flowing links for the test and download the Simple CSS Compressor Script.
The process takes place in a .php file which I call index.php.. Follow these steps to create a simple CSS compressor.
-
Main function
function compress_css($css_codes) { $buffer =$css_codes; // Remove comments $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); // Remove whitespace $buffer = str_replace(array(' ', ' ',' '), ' ', $buffer); $buffer = str_replace(array("\r\n", "\r", "\n", "\t"), '', $buffer); $buffer = str_replace(array('{ ',' {'), '{', $buffer); $buffer = str_replace(array('} ',' }'), '}', $buffer); $buffer = str_replace(array(': ',' :'), ':', $buffer); $buffer = str_replace(array(' ;','; '), ';', $buffer); $buffer = str_replace(array(' ,', ', '), ',', $buffer); $buffer = str_replace(array(' .'), ' .', $buffer); $buffer = str_replace(array(' #'), ' #', $buffer); echo $buffer; }
Create an index.php file and add this function to it. This function is the main part of our CSS compressor. It will remove comments, white spaces, and line breaks from your CSS script.
-
CSS input form
<form action="" method="post"><textarea name="css" rows="8" placeholder="Put your CSS Code here:"></textarea> <input name="submit" type="submit" value="Compress" /></form>
Add this form into your index.php file. By this form, you can submit your CSS script for compress.
-
Display Compressed CSS
<?php if($_SERVER['REQUEST_METHOD'] == 'POST' && ($css=trim($_POST['css']))) { echo '<p style="text-align: left;"><strong>Cumpressed CSS:</strong></p> <textarea class="message" cols="120" rows="10">'; compress_css($css); echo '</textarea>'; } ?>
Add this code wherever you want in your index.php file. It will display the compressed CSS script.
Please follow the above links to test and download this script. If you have any bug report or suggestion for my script please comment it below. Please share it with your friends if you like this script.