用PHP压缩CSS

原文链接:http://abeautifulsite.net/2009/11/compressing-css-with-php/

原文:

Here is a short PHP function that removes comments and whitespace from your CSS. If you happen to be generating your stylesheet dynamically, try wrapping this around the output to reduce the overall size.function compress\_css($css) { / Remove comments $css = preg\_replace('!\*[\^*]*\*+([\^/][\^*]*\*+)*/!', '', $css); // Remove whitespace $css = str\_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css); return $css; }

Dont' forget that, if you are using PHP to output CSS, you'll need to serve the correct headers:header("Content-type: text/css"); header("Expires: " . gmdate("D, d M Y H:i:s", (time() + 604800000)) . " GMT");

The second line tells the browser to cache the styles for seven days. You can adjust that accordingly based on your preferences.

// Remove comments
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
// Remove whitespace
$css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css);
return $css;
}
// Serve the correct headers
header("Content-type: text/css");
header("Expires: " . gmdate("D, d M Y H:i:s", (time() + 604800000)) . " GMT");

上面的英文很简单,相信不用翻译了。