How can PHP be used to modify CSS files dynamically during page loading for optimal performance?

To dynamically modify CSS files during page loading for optimal performance, PHP can be used to combine and minify multiple CSS files into a single file. This reduces the number of HTTP requests needed to load the page, resulting in faster loading times. Additionally, PHP can be used to cache the minified CSS file to further improve performance.

<?php
$cssFiles = array('style1.css', 'style2.css', 'style3.css');

$minifiedCss = '';
foreach ($cssFiles as $file) {
    $minifiedCss .= file_get_contents($file);
}

$minifiedCss = minifyCss($minifiedCss);

file_put_contents('combined.min.css', $minifiedCss);

function minifyCss($css) {
    $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
    $css = str_replace(': ', ':', $css);
    $css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css);
    
    return $css;
}
?>