Skip to content

Instantly share code, notes, and snippets.

@BoboTiG
Forked from brentonstrine/css-compress.php
Last active July 12, 2016 17:03
Show Gist options
  • Save BoboTiG/8bdab4efee08c7987b9dd5d8d6223465 to your computer and use it in GitHub Desktop.
Save BoboTiG/8bdab4efee08c7987b9dd5d8d6223465 to your computer and use it in GitHub Desktop.
More removes.
<?php
/**
* On-the-fly CSS Compression
* Copyright (c) 2009 and onwards, Manas Tungare.
* Creative Commons Attribution, Share-Alike.
*
* In order to minimize the number and size of HTTP requests for CSS content,
* this script combines multiple CSS files into a single file and compresses
* it on-the-fly.
*
* To use this in your HTML, link to it in the usual way:
* <link rel="stylesheet" type="text/css" media="screen, print, projection" href="/css/compressed.css.php" />
*/
/* Add your CSS files to this array (THESE ARE ONLY EXAMPLES) */
$cssFiles = array(
'ads.css',
'formatting.css',
'pagesections.css',
'print.css',
'screen.css',
'sidebar.css',
);
$buffer = '';
foreach ($cssFiles as $cssFile) {
$buffer .= file_get_contents($cssFile);
}
// Remove comments
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
// Remove whitespace
$buffer = str_replace(array("\r\n", "\r", "\n", "\t"), '', $buffer);
// Collapse adjacent spaces into a single space
$buffer = preg_replace('/ {2,}/', ' ', $buffer);
// Remove spaces that might still be left where we know they aren't needed
$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(' [', '[', $buffer);
// Remove space after colons
$buffer = str_replace(': ', ':', $buffer);
// Remove useless semicolon
$buffer = str_replace(';}', '}', $buffer);
// Remove useless units
$buffer = preg_replace('/([:,])0(ch|cm|em|ex|in|mm|pc|pt|px|rem|vh|vmin|vmax|vw%)/', '${1}0', $buffer);
// Remove trailing 0 in values
$buffer = preg_replace('/([\(:; ])0\./', '${1}.', $buffer); // 0.1 => .1
$buffer = preg_replace('/(\.\d+?)0+\b/', '$1', $buffer); // 10.500 => 10.5
// Outout data
ob_start('ob_gzhandler');
header('Cache-Control: public');
header('Expires: '.gmdate('D, d M Y H:i:s', time() + 86400).' GMT');
header('Content-type: text/css');
echo($buffer);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment