我想出了自己的粗略解决方案,并创建了一个类来做我正在寻找的事情。我的来源在底部引用。
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]);
}
}
您可以按如下方式运行它:
$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");
输出如下:
font-size:12px;border:1px solid #EEE
只要注释不在选择器内,此解决方案甚至适用于 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