I have a php module that takes care of finding all the css files in a folder, " minifying " them and writing all the content in a new css.
private function cssFile($css_file, $widget_id = '') {
$css = '';
$css .= file_get_contents($css_file);
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
$css = str_replace(': ', ':', $css);
$css = str_replace(array("\n", "\t", ' ', ' ', ' '), '', $css);
return $css;
}
How can I add a prefix to each of the classes and Ids?
I can't do one str_replace
because it would affect the colors:rgba(0,0,0,0.5), #fff;
Through Regex it was impossible for me since there are values within the css that cannot be differentiated with a single pattern, example #Id , #comment , #fff . Although I am not proud of my code based on str_replace it is the only thing that works correctly for me.
I share it in case someone finds it useful:
You could search for all
#
and.
that are followed by{
without having any}
in between.RegEx
Description
[#.]
- Matches 1 character that is#
or.
\K
- Reset the match (so that the#
or.
is not included in the replacement)(?=[a-z0-9][^{}]*+{)
Lookahead (has to match, but doesn't consume characters) for:[a-z0-9]
- The class name or id should start with a letter or number[^{}]*+
- followed by any character other than{
or}
{
- and then the{
one that opens the style./i
- To match case.Code
Example
Result
Demo en Ideone
Note: It is assumed that you have already deleted comments before this feature. And maybe it could fail with some weird example, but in that case, add that example in the question and I'll adapt it.