Scripts

CSS compressor

Na aanleiding van het "CSS Parser (ECSS)" script heb ik een functie gemaakt die alle overbodige tekens uit een CSS bestand verwijderd. De functie is eenvoudig te gebruiken. Je hoeft alleen het pad van het CSS bestand als parameter op te geven. Voorbeeld:

css-compressor
<?php
/**
 * Verwijderd nutteloze tekens uit een CSS bestand.
 *
 * @param string $_sFullPath			| Volledige pad naar het CSS bestand (b.v.: "c:\pad\style.css" of "/foo/bar/style.css")
 * @return string / boolean false
 */
function compress_css_file( $_sFullPath )
{
	if( !file_exists($_sFullPath) )
	{
		return false;
	}
	
	# Lees CSS bestand in
	$sContent = file_get_contents($_sFullPath);
	
	# Verwijder CSS kommentaar
	$sContent = preg_replace('/\/\*.*?\*\//s', '', $sContent);
	
	# Verwijder alle enters en tabs uit de inhoud van het CSS bestand
	$sContent = str_replace(array("\r", "\n", "\t"), '', $sContent);
	
	# Whitespaces rond bepaalde tekens  verwijderen
	$sContent = preg_replace('/\s*({|}|;|:|,)\s*/', '$1', $sContent);
	
	# Verwijder alle dubbele spaties
	$sContent = preg_replace('/ {2,}/', '', $sContent);
	
	# Grijp alle {....} blokken
	if( preg_match_all('/{.*?}/s', $sContent, $aMatch) )
	{
		$aMatch[0] = array_unique($aMatch[0]);
		
		foreach( $aMatch[0] as $k => $v )
		{
			# Verwijder laatste ";" van laatste statement in een blok
			$l = strlen($v);
			if( $v[$l-2] == ';' )
			{
				$v = substr($v, 0, $l-2) . '}';
			}

			# Vervang het nieuw blok met het oude.			
			$sContent = str_replace($aMatch[0][$k], $v, $sContent);
		
		} # end foreach
		
	} # end if
	
	return $sContent;

} # end method compress_css_file
?>

Reacties

0
Nog geen reacties.