Question

I need to edit my css "string" and add #holder selector before every single selector. For example;

I want to change this css string;

/* the css file with comments */ 
.header ul, .footer #div, .selector3 a
{
    box-shadow: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
}

.selector4, .selector5 ul > li, .selector6 a:hover
{
    text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
    -moz-text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
    -webkit-text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
}

as

/* the css file with comments */ 
#holder .header ul, #holder .footer #div, #holder .selector3 a
{
    box-shadow: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
}

#holder .selector4, #holder .selector5 ul > li, #holder .selector6 a:hover
{
    text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
    -moz-text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
    -webkit-text-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
}

I have used this regex to minify the string and it works fine so you can just ignore the comment lines.

preg_replace('@({)\s+|(\;)\s+|/\*.+?\*\/|\R@is', '$1$2 ', $css);

I'm searching a regex method to do it but any other solution also would be appreciated. Thanks in advance.

Was it helpful?

Solution

You can do this:

$pat = '~(?>/\*(?>[^*]++|\*(?!/))*+\*/|{[^}]*+})(*SKIP)(?!)|[^\s,{/][^,{/]++~';
$css = preg_replace($pat, '#holder $0', $css);

The idea is to avoid comments and content inside curly brackets, then you can easily find all selectors with [^\s,{/][^,{/]++.

To do that you put in a group the subpatterns for comments (i.e. /\*(?>[^*]++|\*(?!/))*+\*/) and for content inside curly brackets (i.e. {[^}]*+}), then you force the pattern to fail and forbid backtracking in the matched substrings.

(*SKIP)(?!) is used for that. (*SKIP) forbid to backtrack in all the matched content on his left if the subpattern will fail later. (?!) forces the subpattern to fail ("not followed by nothing" is always false).

OTHER TIPS

You have two choices:

Either you are replacing every class selector, in which case you use:

(\.[\w_\-]+)\b -- example: http://regex101.com/r/kM3dK9

Or you're going to need to specify which ones you're replacing:

(\.(selector4|selector_5|other6))\b -- example: http://regex101.com/r/aC6dR3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top