使用媒体查询和其他终端案例将css解析为php数组

使用媒体查询和其他终端案例将css解析为php数组,php,css,arrays,parsing,Php,Css,Arrays,Parsing,我想把css文件分解成php数组。 我有以下代码: function parseCss($css_str) { $css = array(); // TODO include external css $css_str = preg_replace('/(@import\s+["\'].+["\'];)/', "", $css_str); // Strip all line endings and both single and multiline comme

我想把css文件分解成php数组。 我有以下代码:

function parseCss($css_str) {
    $css = array();

    // TODO include external css
    $css_str = preg_replace('/(@import\s+["\'].+["\'];)/', "", $css_str);

    // Strip all line endings and both single and multiline comments
    $css_str = preg_replace('/\s*(?!<\")\/\*+[^\*]+\*+\/(?!\")\s*/', "", $css_str);

    $css_class = explode("}", $css_str);

    while(list($key, $value) = each($css_class)){

        $aCSSObj = explode("{", $value);
        $cssSelector = strtolower(trim($aCSSObj[0]));
        if($cssSelector){
                // regular class not in media query
                $cssprops[] = $cssSelector;
                $a = explode(";", $aCSSObj[1]);
                while(list($key, $val0) = each($a)){
                    if(trim($val0)){
                        $aCSSSub = explode(":", $val0);
                        $cAtt = strtolower(trim($aCSSSub[0]));
                        if(isset($aCSSSub[1])){
                            $aCSSItem[$cAtt] = trim($aCSSSub[1]);
                        }
                    }
                }
                if((isset($css[$cssSelector])) && ($css[$cssSelector])){
                    $aCSSItem = array_merge($css[$cssSelector], $aCSSItem);
                }
                $css[$cssSelector] = (isset($aCSSItem)) ? $aCSSItem : null ;
                unset($aCSSItem);       
        }
        if(strstr($cssSelector, ",") && !strstr($cssSelector, "@media")){
            $aTags = explode(",", $cssSelector);
            print_r($aTags);
            foreach($aTags as $key0 => $value0){
                $css[$value0] = $css[$cssSelector];
            }
            unset($css[$cssSelector]);
        }
    }
    unset($css_str, $css_class, $aCSSSub, $aCSSItem, $aCSSObj);
    return $css;
}
它将返回被剪切的代码

所以结果应该是这样的:

top:expression((-20+(document.documentElement.clientHeight ?document.documentElement.clientHeight/2:document.body.clientHeight/2)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop:document.body.scrollTop))+'px')
Array
(
    [selector] => array (
            [prop] => value
            [prop2] => value
    )

    [@media handheld,only screen and (max-width:320px)] => array(
        [selector] => array(
                [prop] => value
                [prop2] => value
        )
    )
)
我如何使它工作?

解决了这个问题! 最后,我使用CSSTidy来解析css,它做得很好!

对于一个简单的CSS来说太多了,我应该说,好吧,我愿意使用替代代码,对数组进行CSS解析,并支持最终用例…从CSS 3是一个计算通用指令集这一事实开始,您可能会使用PCRE模式,然而,不要期望它像你在问题中概述的那样微不足道。-规则。你最后的评论:据我所知,你首先需要用PHP编写一个好的CSS解析器,到目前为止还没有。一个能够解析CSS选择器(只有选择器)的部分CSS解析器可以在中找到,但是它不会返回数组(还没有)。我知道的另一个将选择器解析为AST的解析器是。