Having as a base this question (posted by @skrilled in the comments) I made an example of how you can parse a css with regular expression.
We can accomplish this by doing a two steps matching of the String.
1) Firstly we retrieve the class (or id name) and the abstraction of the attributes in a string (I mean, all the attributes in one string).
This regex fulfills pretty well the task: ([#\.][a-z0-9]*?\.?.*?)\s?\{([^\{\}]*)\}
2) Had the attributes string, we can now spend a regex to parse it and create a new array. Using this simple regex we can retrieve the second part: ([^\;]*);
In the code this would be something like:
function parseCss($cssString){
//Parsing the class or id name + the attributes
$regex = "/([#\.][a-z0-9]*?\.?.*?)\s?\{([^\{\}]*)\}/m";
preg_match_all($regex, $cssString, $classes, PREG_PATTERN_ORDER);
if(sizeof($classes[1]) > 0){
//organize a new proper array "$parsedCss"
foreach($classes[1] as $index => $value){
$parsedCss[$index][0] = $value; //class or id name
}
foreach($classes[2] as $index => $value){
//Parsing the attributes string
$regex = "/([^\;]*);/m";
preg_match_all($regex, $value, $returned_attributes, PREG_PATTERN_ORDER);
if(sizeof($returned_attributes[1]) > 0){
$parsedCss[$index][1] = $returned_attributes[1]; // array of attributes
}
}
}
return $parsedCss;
}
Then you can just print:
echo '<pre>';
$css = "#header { background: red; font-size: 14px; color:white; }#header { background: red; font-size: 14px; color:white; }";
print_r(parseCss($css));
And the result would be:
Array
(
[0] => Array
(
[0] => #header
[1] => Array
(
[0] => background: red
[1] => font-size: 14px
[2] => color:white
)
)
[1] => Array
(
[0] => #header
[1] => Array
(
[0] => background: red
[1] => font-size: 14px
[2] => color:white
)
)
)