Parsing CSS by regex

前端 未结 8 1775
时光说笑
时光说笑 2020-11-27 17:37

I\'m creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can\'t get it to

8条回答
  •  情话喂你
    2020-11-27 18:07

    I wrote a piece of code that easily parses CSS. All you have to do is do a couple of explodes really... The $css variable is a string of the CSS. All you have to do is do a print_r($css) to get a nice array of CSS, fully parsed.

    $css_array = array(); // master array to hold all values
    $element = explode('}', $css);
    foreach ($element as $element) {
        // get the name of the CSS element
        $a_name = explode('{', $element);
        $name = $a_name[0];
        // get all the key:value pair styles
        $a_styles = explode(';', $element);
        // remove element name from first property element
        $a_styles[0] = str_replace($name . '{', '', $a_styles[0]);
        // loop through each style and split apart the key from the value
        $count = count($a_styles);
        for ($a=0;$a<$count;$a++) {
            if ($a_styles[$a] != '') {
                $a_key_value = explode(':', $a_styles[$a]);
                // build the master css array
                $css_array[$name][$a_key_value[0]] = $a_key_value[1];
            }
        }               
    }
    

    Gives you this:

    Array
    (
        [body] => Array
            (
                [background] => #f00
                [font] => 12px arial
            )
    )
    

提交回复
热议问题