Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Last active Dec 17, 2015
Embed
What would you like to do?
Rewrite multiple CSS links (and HEAD styles) to a single sheet.
# Uncomment (remove the hash from) ONLY ONE of the following lines (first one is already uncommented):
AddHandler application/x-httpd-php .html .htm
# AddHandler application/x-httpd-php5 .html .htm
# AddType application/x-httpd-php .html .htm
# AddHandler x-httpd-php .html .htm
# end of the one-line options (use the first one that doesn't cause an error on your server).
# Or, if you are stranded on GoDaddy, uncomment BOTH following lines:
# AddType application/x-httpd-php .htm .html
# AddHandler x-httpd-php .htm .html
# change the following path to reflect YOUR server, not mine
php_value auto_prepend_file /data/www/scripty/masher/masher.php
<?php
ob_start();
$code = file_get_contents($_SERVER['SCRIPT_FILENAME']);
$now = filemtime($_SERVER['SCRIPT_FILENAME']);
ob_end_clean();
$out = array();
$sheets = array();
$inline = array();
$style = '';
$prefix = '';
$ending = '>';
$base = str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']);
$base = preg_split('/[\/\.]/', $base, -1, PREG_SPLIT_NO_EMPTY);
array_pop($base);
$base = implode('_', $base);
$lines = preg_split('/[\n\r]+/', $code, -1, PREG_SPLIT_NO_EMPTY);
$styling = false;
foreach($lines as $line){
if($styling && preg_match('/<\/style>/i', $line)){
$styling = false;
}elseif(!$styling && preg_match('/<style/i', $line)){
$styling = true;
}elseif($styling && preg_match('/<!--|-->/', $line)){
//ignore the comment
}elseif($styling){
$inline[] = trim($line);
}elseif(preg_match('/<\/head>/i', $line)){
$out[] = preg_replace('/<\/head>/i', '', $line);
$out[] = ' <link rel="stylesheet" href="' . $prefix . '/' . $base . '.css"' . $ending;
$out[] = '</head>';
}elseif(preg_match('/<link .*?rel="stylesheet/i', $line)){
if(preg_match('/\/>/', $line)) $ending = '/>';
$sheet = preg_replace('/.+?href="(.+?)"[^>]*>/i','$1', $line);
if(!preg_match('/https?:\/\//i',$sheet)){
$sheets[] = $sheet;
$prefix = dirname($sheet);
}else{
$out[] = $line;
}
}else{
$out[] = $line;
}
}
$offset = '';
foreach($sheets as $sheet){
if(empty($offset)) $offset = dirname($_SERVER['SCRIPT_FILENAME']) . '/' . dirname($sheet);
$link = dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $sheet;
if(file_exists($link)){
$style .= file_get_contents($link) . "\n";
}else{
$link = "\t<link rel=\"stylesheet\" href=\"$link\" type=\"text/css\"$ending\n</head>";
$code = preg_replace('/<\/head>/', $link);
}
}
$style .= implode("\n", $inline);
file_put_contents($offset . '/' . $base . '.css', $style);
print implode("\n", $out);
exit;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment