I am trying to write a function that converts a short hand css declaration of background to long hand. I’ve written the below function but it has a couple of issues. One it doesn’t take into account that background-color can be colour values such as black, yellow. In addition, what if some the properties contain inherit and none? Here is an example:
url('http://2.bp.blogspot.com/-h28qvOsfm1c/TaGyO_qAFcI/AAAAAAAAA9w/I7zPQLy0zVM/s640/funny-image.jpg') inherit inherit 0 0 #FFFFFF;
Convert the above to CSS long hand. Here is my function, can it be improved to cover other cases?
function rewrite_background($b){
$long_hand = "";
$count = count($b);
for($i=0; $i < $count; $i++){
if(stripos($b[$i], '#') !== false){
$long_hand .= 'background-color: '.$b[$i].'; ';
unset($b[$i]);
}else if(stripos($b[$i], 'url') !== false){
$long_hand .= 'background-image: '.$b[$i].'; ';
unset($b[$i]);
}else if((stripos($b[$i], 'repeat') !== false) || (stripos($b[$i], 'no-repeat') !== false) || (stripos($b[$i], 'repeat-x') !== false) || (stripos($b[$i], 'repeat-y') !== false)){
$long_hand .= 'background-repeat: '.$b[$i].'; ';
unset($b[$i]);
}else if((stripos($b[$i], 'scroll') !== false) || (stripos($b[$i], 'fixed') !== false)){
$long_hand .= 'background-attachment: '.$b[$i].'; ';
unset($b[$i]);
}else{
// not recognized
}
}
$b = array_values($b);
if(isset($b[0])) $long_hand .= 'background-position: '.$b[0].' '.$b[1].';';
return $long_hand;
}
Class to Parse CSS Background Shortcuts
This class will parse just about any line of background shortcut properties in any order, including those that are invalid according to the specs. For instance,
background: top topis treated asbackground-position: center top.All color values are fully supported, including: rgb, rgba, hls, hlsa, case-insensitive short-form hex (e.g. #fff), case-insensitive long-form hex (e.g. #123Abc), and case-insensitive color names.
!importantis now supported.inheritseemed as though it would be the most challenging problem, but turns out to be the simplest. For this property I referred to http://reference.sitepoint.com/css/inheritvalue, which states:To deal with ambiguity, this class simply ignores everything else (except !important) and applies inherit to all properties as if you had used
background: inherit.The Code
Example Usage
This class was developed through extensive analysis of the w3c specifications for the CSS background property. Additional CSS properties would require the same analytical treatment.