PHP: ottimizzare i file CSS

PHP: ottimizzare i file CSS

L'ottimizzazione 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:


if(!defined('PATH')) {
    exit;
}
header( 'Content-Type: text/css' );

$file = isset( $_GET[ 'css' ] ) ? $_GET[ 'css' ] : '';
$base_path = PATH . '/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="https://sito.tld/inc/minify.php?css=style.css" type="text/css" media="screen">
</head>

Torna su