我正在寻找实现这一目标的方法。
#header { background: red; font-size: 14px; color:white; }
我希望能够将这个(以及更多这些在同一个文件中)解析/正则化为一个看起来像这样的数组。
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;
等
我已经尝试谷歌数小时了,而且我在正则表达式和多维数组的丛林中完全迷失了。
任何人都知道如何实现这一目标?
答案 0 :(得分:0)
以this question 为基础(由@skrilled在评论中发布)我举例说明了如何使用正则表达式解析css。
我们可以通过执行String的两步匹配来实现此目的。
1)首先,我们在字符串中检索类(或id名称)和属性的抽象(我的意思是,一个字符串中的所有属性)。
This regex完成任务:([#\.][a-z0-9]*?\.?.*?)\s?\{([^\{\}]*)\}
2)如果有属性字符串,我们现在可以使用正则表达式来解析它并创建一个新数组。使用this simple regex我们可以检索第二部分:([^\;]*);
在代码中,这将是:
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
)
)
)