Come posso minimizzare i file CSS con PHP?

La minimizzazione dei file CSS tramite PHP avviene mediante l'eliminazione dello spazio bianco superfluo. La tecnica รจ molto semplice.

Creiamo uno script PHP con il seguente codice:


header( 'Content-Type: text/css' );

$file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
$base_path = $_SERVER['DOCUMENT_ROOT'] . '/assets/css/';

if( preg_match( '/\.css$/', $file ) ) {
	$full_path = $base_path . $file;
	if( file_exists( $full_path ) ) {
		$content = file_get_contents( $full_path );
		echo minify( $content );	
	}
}



function minify( $css ) {
	$css = preg_replace( '#\s+#', ' ', $css );
	$css = preg_replace( '#/\*.*?\*/#s', '', $css );
	$css = str_replace( '; ', ';', $css );
	$css = str_replace( ': ', ':', $css );
	$css = str_replace( ' {', '{', $css );
	$css = str_replace( '{ ', '{', $css );
	$css = str_replace( ', ', ',', $css );
	$css = str_replace( '} ', '}', $css );
	$css = str_replace( ';}', '}', $css );

	return trim( $css );
}

Quindi possiamo usare il nostro script in questo modo:


<head>
<link rel="stylesheet" href="http://sito/inc/minify.php?css=style.css" type="text/css" media="screen" />
</head>

Torna su