Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a prefix to all selectors in a excerpt of CSS with PHP?

Tags:

css

php

parsing

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

like image 698
JCOC611 Avatar asked Sep 02 '25 06:09

JCOC611


2 Answers

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

like image 167
Jan-Henk Avatar answered Sep 04 '25 19:09

Jan-Henk


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.

like image 23
JohnyFree Avatar answered Sep 04 '25 19:09

JohnyFree