Reputation: 9269
I retrieve with PHP a css file in my database.
So i have : $mycss = "SOME CSS SOME CSS SOME CSS"
In this $mycss, i can have :
div.coul01,.red,.coul01{
color:#663333;
}
div.coul02,.blue,.coul02{
color:#3366CC;
}
For this example, i need to retrive in PHP, for each instruction that begins with div. the second element, here "red" and "blue".
Do you have any ideas ? Thanks !
Upvotes: 4
Views: 131
Reputation: 10067
If you really don't want to use any library and want to stick to regular expressions, this will work for you:
<?php
$mycss = "body,div.coul01,.white,.coul01{
color:#000000;
}
div.coul01,.red,.coul01{
color:#663333;
}
div.coul02,.blue,.coul02{
color:#3366CC;
}
div.coul02,.grey,.coul02{
color:#C0C0C0;
}";
preg_match_all("/^div\.[^,{]*,[\.#](\w+)/ms", $mycss, $matches, PREG_PATTERN_ORDER, 0);
?>
and then in your $matches
variable you will have something like this:
$matches[0][0] div.coul01,.red
$matches[0][1] div.coul02,.blue
$matches[0][2] div.coul02,.grey
$matches[1][0] red
$matches[1][1] blue
$matches[1][2] grey
$matches[1]
is what you are looking for
Upvotes: 1
Reputation: 19889
I would suggest using a CSS parser such as Sabberworm. You could also try this library, which I've seen a few people recommend. There is also a PEAR package that you might want to look at called HTML_CSS. Note that it is currently not being maintained. Personally, I'd stay far away from writing custom regex expressions for this kind of thing, simply because I've seen projects like this "take on wings" and lead to messy regex-riddled code that is difficult to maintain as the project expands and more features are added. One minute you're wanting everything that starts with div, the next you're wanting to control h1, span and p styles.
Upvotes: 0
Reputation: 721
You could use explode()
with the comma as the separator, but a more elegant solution would be to use a PHP CSS parser, such as https://github.com/sabberworm/PHP-CSS-Parser
It's more flexible.
Upvotes: 0