PHP CSS分析器 - 字符串的选择器声明

0pt*_*1z3 5 css php parsing css-parsing

我希望能够读取CSS文件,并能够将给定选择器的所有声明提取到字符串中.例如,给定以下样式表:

h1 {
  font-size: 15px;
  font-weight: bold;
  font-style: italic;
  font-family: Verdana, Arial, Helvetica, sans-serif;
}

div.item {
  font-size: 12px;
  border:1px solid #EEE;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够调用并获得div.item,例如:

$css->getSelector('div.item');
Run Code Online (Sandbox Code Playgroud)

哪个应该给我一个字符串:

font-size:12px;border:1px solid #EEE;
Run Code Online (Sandbox Code Playgroud)

我一直在寻找,但找不到可以做到这一点的解析器.有任何想法吗?

仅供参考:我需要能够从CSS转换选择器并将动态嵌入到电子邮件中的HTML元素中.

解决方案 编辑:我想出了自己的原始解决方案并创建了一个类来完成我想要的工作.请看下面我自己的答案.

0pt*_*1z3 2

我想出了自己的粗略解决方案,并创建了一个类来完成我正在寻找的事情。我的资料来源在底部引用。

class css2string {
    var $css;

    function parseStr($string) {
        preg_match_all( '/(?ims)([a-z0-9, \s\.\:#_\-@]+)\{([^\}]*)\}/', $string, $arr);
        $this->css = array();
        foreach ($arr[0] as $i => $x)
        {
            $selector = trim($arr[1][$i]);
            $rules = explode(';', trim($arr[2][$i]));
            $this->css[$selector] = array();
            foreach ($rules as $strRule)
            {
                if (!empty($strRule))
                {
                    $rule = explode(":", $strRule);
                    $this->css[$selector][trim($rule[0])] = trim($rule[1]);
                }
            }
        }
    }

    function arrayImplode($glue,$separator,$array) {
        if (!is_array($array)) return $array;
        $styleString = array();
        foreach ($array as $key => $val) {
            if (is_array($val))
                $val = implode(',',$val);
            $styleString[] = "{$key}{$glue}{$val}";

        }
        return implode($separator,$styleString);   
    }

    function getSelector($selectorName) {
        return $this->arrayImplode(":",";",$this->css[$selectorName]);
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式运行它:

$cssString = "
h1 {
  font-size: 15px;
  font-weight: bold;
  font-style: italic;
  font-family: Verdana, Arial, Helvetica, sans-serif;
}

div.item {
  font-size: 12px;
  border:1px solid #EEE;
}";

$getStyle = new css2string();
$getStyle->parseStr(cssString);
echo $getStyle->getSelector("div.item");
Run Code Online (Sandbox Code Playgroud)

输出如下:

font-size:12px;border:1px solid #EEE
Run Code Online (Sandbox Code Playgroud)

该解决方案甚至适用于 CSS 文件中的注释,只要注释不在选择器内即可。

参考文献: http://www.php.net/manual/en/function.implode.php#106085 http://stackoverflow.com/questions/1215074/break-a-css-file-into-an-array-with -php