|
Posted by Sandman on 11/07/44 11:26
In article <1126557506.627491.241930@g49g2000cwa.googlegroups.com>,
"kevinC" <kcallahan@gmail.com> wrote:
> Hello,
>
> I'm trying to parse out the properties of a class definition from a css
> file and am running into issues trying to write the reg. expression:
>
> h1 {
> font-family: Verdana, Arial, Helvetica, sans-serif;
> font-size: 16px;
> font-weight: bold;
> color: #003399;
> }
> ...
>
> I need the results in:
> array[i][0] = "h1"
> array[i][1] = "
> font-family: Verdana, Arial, Helvetica, sans-serif;
> font-size: 16px;
> font-weight: bold;
> color: #003399;"
>
> Any idea? I tried looking online for an example and can't find anything
> that works with php's preg_match_all() function...
This is how I solved it:
<?
# read stylesheets from a file
$filen=join("", file($stylesheetfile));
# remove everything between /* and */
$filen = preg_replace("!/\*.*?\*/!ms", "", $filen);
# remove whitespaces after semicolons
$filen = preg_replace("/;\s+/m", "; ", $filen);
# remove whitespaces after {
$filen = preg_replace("/{\s+/m", "{ ", $filen);
# remove whitespace before {
$filen = preg_replace("/\s+{/m", " {", $filen);
# replace several newlines with one
$filen = preg_replace("/\n{2,}/m", "\n", $filen);
# Leading whitespace
$filen = preg_replace("/^\s*/m", "", $filen);
# Multiple whitespaces to one
$filen = preg_replace("/ +/m", " ", $filen);
# Split every row and put in array as:
# filestylearray[selector][attribute]="value";
foreach(split("\n", $filen) as $line){
preg_match("/^(.*){\s*(.*)\s*;\s*}\s*$/", $line, $m);
foreach(split(";",$m[2]) as $attribline){
$a=split(":", trim($attribline));
$stylearray[strtolower(trim($m[1]))][trim($a[0])]=trim("$a[1]");
}
}
?>
It doesn't sort it like you want it to, but it can be tweaked.
Your example would end up in:
Array
(
[h1] => Array
(
[font-family] => Verdana, Arial, Helvetica, sans-serif
[font-size] => 16px
[font-weight] => bold
[color] => #003399
)
)
--
Sandman[.net]
[Back to original message]
|