Find something in CSS with PHP

I am extracting a css file from PHP in my database.

So I have: $mycss = "SOME CSS SOME CSS SOME CSS"

In this $ mycss, I can:

 div.coul01,.red,.coul01{ color:#663333; } div.coul02,.blue,.coul02{ color:#3366CC; } 

In this example, I need to extract PHP, for each instruction starting with a div. the second element, here is red and blue.

Do you have any ideas? Thanks!

+4
source share
3 answers

If you really don't want to use any library and want to stick with 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

Example

+1
source

You can use explode() with a comma as a separator, but a more elegant solution would be to use a PHP CSS parser, for example https://github.com/sabberworm/PHP-CSS-Parser

It is more flexible.

0
source

I would suggest using a CSS parser like Sabberworm . You can also try this library , which I saw when some people recommend. There is also a PEAR package, which you can see on the HTML_CSS name. Please note that it is not currently supported. Personally, I would stay away from writing custom regex expressions for this kind of thing, simply because I saw projects like β€œtake wings” and lead to messy program code that is hard to maintain as the project expands and additional features are added . In one minute, you want everything that starts with a div, and then you want to control the h1, span, and p styles.

0
source

All Articles