Christian
Christian

Reputation: 28125

PHP Simple CSS string parser

I need to parse some CSS code like:

color: black;
font-family:"Courier New";
background:url('test.png');
color: red;
--crap;

Into:

array (
    'color'=>'red',
    'font-family'=>'"Courier New"',
    'background'=>'url(\'test.png\')',
    '--crap'=>''
)

Upvotes: 2

Views: 1844

Answers (4)

codaddict
codaddict

Reputation: 454922

You can try:

$result = array();
if(preg_match_all('/\s*([-\w]+)\s*:?\s*(.*?)\s*;/m',$input,$m))
        var_dump($m);
        // $m[1] contains all the properties
        // $m[2] contains their respective values.
        for($i=0;$i<count($m[1]);$i++) {
                $result[$m[1][$i]] = $m[2][$i];
        }
}

Upvotes: 0

fabrik
fabrik

Reputation: 14365

Why don't take a look at CSSTidy?

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57258

I found this few weeks back and looks interesting.

http://websvn.atrc.utoronto.ca/wsvn/filedetails.php?repname=atutor&path=/trunk/docs/include/classes/cssparser.php

Example:

$Parser = new cssparser();
$Results = $Parser->ParseStr("color: black;font-family:"CourierNew";background:url('test.png');color: red;--crap;");

Upvotes: 0

Matthew
Matthew

Reputation: 48284

Here's a simple version:

    $a = array();
    preg_match_all('/^\s*([^:]+)(:\s*(.+))?;\s*$/m', $css, $matches, PREG_SET_ORDER);
    foreach ($matches as $match)
            $a[$match[1]] = isset($match[3]) ? $match[3] : null;

Sample output:

array(4) {
  ["color"]=>
  string(3) "red"
  ["font-family"]=>
  string(13) ""Courier New""
  ["background"]=>
  string(15) "url('test.png')"
  ["--crap"]=>
  NULL
}

Not tested with anything except your source data, so I'm sure it has flaws. Might be enough to get you started.

Upvotes: 2

Related Questions