Issue
I wanted to break a css file into an array with PHP.
Ex:
#selector{ display:block; width:100px; }
#selector a{ float:left; text-decoration:none; }
Into a php array...
array(2) {
["#selector"] => array(2) {
[0] => array(1) {
["display"] => string(5) "block"
}
[1] => array(1) {
["width"] => string(5) "100px"
}
}
["#selector a"] => array(2) {
[0] => array(1) {
["float"] => string(4) "left"
}
[1] => array(1) {
["text-decoration"] => string(4) "none"
}
}
}
Any ideas?
Oh : Edit : I am not worried about ill formed CSS files in this instance. Doesn't ahve to be bulletproof as long as its not greedy
Solution
This should do it:
<?php
$css = <<<CSS
#selector { display:block; width:100px; }
#selector a { float:left; text-decoration:none }
CSS;
//
function BreakCSS($css)
{
$results = array();
preg_match_all('/(.+?)\s?\{\s?(.+?)\s?\}/', $css, $matches);
foreach($matches[0] AS $i=>$original)
foreach(explode(';', $matches[2][$i]) AS $attr)
if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal
{
list($name, $value) = explode(':', $attr);
$results[$matches[1][$i]][trim($name)] = trim($value);
}
return $results;
}
var_dump(BreakCSS($css));
Quick Explanation: The regexp is simple and boring. It just matches all "anything, possible space, curly bracket, possible space, anything, close curly bracket". From there, the first match is the selector, the second match is the attribute list. Split that by semicolons, and you're left with key/value pairs. Some trim()'s in there to get rid of whitespace, and that's about it.
I'm guessing that your next best bet would probably be to explode the selector by a comma so that you can consolidate attributes that apply to the same thing etc., but I'll save that for you. :)
Edit: As mentioned above, a real grammar parser would be more practical... but if you're assuming well-formed CSS, there's no reason why you need to do anything beyond the simplest of "anything { anything }". Depends on what you want to do with it, really.
Answered By - Nathan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.