php用正则表达式获取css

I'm trying to get css selector + styles with a regexp but there is always a problem...

So do you have an idea (exemple ?) of a regexp do get this:

array(
[0] => "div {
    background: red;
    color: blue;
}",
[1] => "section {
    /* comment with bad idea } <- this break regexp [^}]+ */
    background: blue;
    color: red;
}"
);

fom this css:

div {
    background: red;
    color: blue;
}

section {
    /* comment with bad idea } <- this break regexp [^}]+ */
    background: blue;
    color: red;
}

Thx

I finally did it by another way. First, I start by quoting the undesired symbols with these regex

string = string
.replace(/(')([^']*)(')/ig, function(found){

    return found.replace(/([\[\]\s\,\#\.\:\>\~])/ig, "\/\/$1\\\\");

})
.replace(/(\")([^\"]*)(\")/ig, function(found){

    return found.replace(/([\[\]\s\,\#\.\:\>\~])/ig, "\/\/$1\\\\");

});

Then, I split the string with another regexp:

string = string.split(/(?!\/\/)([\s\>\,])(?!\\\\)|(?=(?!\/\/)[\#\.\[\:](?!\\\\))/ig);

And, to finish, if( string[x].match(/^[a-z]+$/ig) ){..}; it is a tagName

If you see something bad, I'm listening to you.

Edit :

Oups ! I forgot my answer was about php, sorry. But I apply the same method for php, except lookBefore simplify and reduce the regexp to only one, then split...

J

Regular expression will always fail because you have the } inside the comment.

It would only work if you ran a regular expression that removes all comments before the one that matches the styles.

How about:

\S+\s*{(.*?)}(?![^*]*\*/)

RegExr Example

Explanation:

\S+\s*       put your selector regex in place of this 
{(.*?)}      lazy match everything to a } 
(?![^*]*\*/) check that the next * after the } is not the start of a */

This will not match styles that are completely commented out. e.g /* div { ... } */ but it's unclear what you would want to happen in this case anyway.

Keep using whatever you're using to match the selectors instead of \S+\s* (which I just used for examples sake).