Ok so lets say I have a variable $css
that contains some CSS code. What I want to do is to add a certain text in front of each selector. So for example, the following code:
#hello, .class{width:1px;height:1px;background-color:#AAA;}
div{font-size:1px}
input, a, span{padding:4px}
Would be converted into:
#someId #hello, #someId .class{ ... }
#someId div{ ... }
#someId input, #someId a, #someId span{ ... }
I have been trying to use several explode()
s. However, I haven't been able to accomplish the task effectively. Any thoughts?
Thanks! JCOC611
Based on Jon's suggestion I wrote the following code:
<?php
$prefix = '#someId';
$css = '#hello, .class{width:1px;height:1px;background-color:#AAA;}
div{font-size:1px}
input, a, span{padding:4px}';
$parts = explode('}', $css);
foreach ($parts as &$part) {
if (empty($part)) {
continue;
}
$subParts = explode(',', $part);
foreach ($subParts as &$subPart) {
$subPart = $prefix . ' ' . trim($subPart);
}
$part = implode(', ', $subParts);
}
$prefixedCss = implode("}\n", $parts);
echo $prefixedCss;
To see that it works see http://codepad.org/bqRd83gu
I wrote improved version because I also need media query. This is my function based on Jan's answer:
function getPrefixedCss($css,$prefix){
$parts = explode('}', $css);
$mediaQueryStarted = false;
foreach ($parts as &$part) {
if (empty($part)) {
continue;
}
$partDetails = explode('{',$part);
if(substr_count($part,"{")==2){
$mediaQuery = $partDetails[0]."{";
$partDetails[0] = $partDetails[1];
$mediaQueryStarted = true;
}
$subParts = explode(',', $partDetails[0]);
foreach ($subParts as &$subPart) {
if(trim($subPart)=="@font-face") continue;
$subPart = $prefix . ' ' . trim($subPart);
}
if(substr_count($part,"{")==2){
$part = $mediaQuery."\n".implode(', ', $subParts)."{".$partDetails[2];
}elseif(empty($part[0]) && $mediaQueryStarted){
$mediaQueryStarted = false;
$part = implode(', ', $subParts)."{".$partDetails[2]."}\n"; //finish media query
}else{
$part = implode(', ', $subParts)."{".$partDetails[1];
}
}
$prefixedCss = implode("}\n", $parts);
return $prefixedCss;
}
It works with media query and also @font-face.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With