0

id 喜欢将 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;
}

但这并没有给我返回一个带有媒体查询的 css 文件。如果在 css 值中有一个“:”符号 - 例如像这样的 IE 表达式:

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
        )
    )
)

我如何使它工作?

4

1 回答 1

0

解决了!最终我使用了 CSSTidy 来解析 css,它做得很好! http://csstidy.sourceforge.net/index.php

于 2013-08-25T01:59:43.633 回答