解析,正则表达式的CSS文件


PHP - Parse, Regex CSS file?

我正在寻找一种方法来实现这一点。

#header { background: red; font-size: 14px; color:white; }

我希望能够解析/regex这个(和更多的这些在同一个文件)到一个数组,看起来像这样。

Array[0] = header
Array[0][0] = background: red;
Array[0][1] = font-size; 14px;
Array[0][2] = color: white;

下一个例子#content就是

Array[1] = content 
Array[1][0] = width: 1200px;

我已经尝试谷歌几个小时了,我完全迷失在正则表达式和多维数组的丛林中。

有谁知道这是怎么实现的吗?

以这个问题(由@ skrril在评论中发布)为基础,我做了一个如何用正则表达式解析css的例子。

可以通过对String进行两步匹配来实现。

1)首先,我们检索类(或id名称)和字符串中属性的抽象(我的意思是,一个字符串中的所有属性)。这个正则表达式很好地完成了任务:([#'.][a-z0-9]*?'.?.*?)'s?'{([^'{'}]*)'}

2)有了属性字符串,我们现在可以使用正则表达式来解析它并创建一个新数组。使用这个简单的正则表达式,我们可以检索第二部分:([^';]*);

在代码中应该是这样的:

function parseCss($cssString){
    //Parsing the class or id name + the attributes
    $regex = "/([#'.][a-z0-9]*?'.?.*?)'s?'{([^'{'}]*)'}/m";
    preg_match_all($regex, $cssString, $classes, PREG_PATTERN_ORDER);
    if(sizeof($classes[1]) > 0){
        //organize a new proper array "$parsedCss"
        foreach($classes[1] as $index => $value){
            $parsedCss[$index][0] = $value; //class or id name
        }
        foreach($classes[2] as $index => $value){  
            //Parsing the attributes string
            $regex = "/([^';]*);/m";
            preg_match_all($regex, $value, $returned_attributes, PREG_PATTERN_ORDER);
            if(sizeof($returned_attributes[1]) > 0){
                $parsedCss[$index][1] = $returned_attributes[1]; // array of attributes
            }
        }
    }
    return $parsedCss;
}

那么你可以直接打印:

echo '<pre>';
$css = "#header { background: red; font-size: 14px; color:white; }#header { background: red; font-size: 14px; color:white; }";
print_r(parseCss($css));

结果是:

Array
(
    [0] => Array
        (
            [0] => #header
            [1] => Array
                (
                    [0] =>  background: red
                    [1] =>  font-size: 14px
                    [2] =>  color:white
                )
        )
    [1] => Array
        (
            [0] => #header
            [1] => Array
                (
                    [0] =>  background: red
                    [1] =>  font-size: 14px
                    [2] =>  color:white
                )
        )
)