0

I need some help creating a multi-dimensional array from CSS. For example:

$css = "body { font-weight:40px; color:#444; } #wrapper { width: 500px; }";

I do have the following code from Split CSS inside the {} to array of key/value pairs but this doesn't do the selector aswell

function BreakCSS($CSS) {
$results = array();

foreach(explode(';', $CSS) AS $attr)
    if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal
    {
        list($name, $value) = explode(':', $attr);
        $results[trim($name)] = trim($value);
    }
return $results;

}

I am not a expert when it comes to this kind of coding. Ideally i would like:

array(
    'body' => array (
        array(
            'font-weight',
            '40',
            'px'
        ),
        array(
            'color',
            '#444',
            ''
        )
    )
)

Furthermore, is there a way of checking to see if !important has been added to the end?

Thanks in advance!

deanhodges
  • 79
  • 1
  • 12
  • Then I have to ask the same thing as they did in the post you're referring to, why not use an already built parser? – M. Eriksson Jul 14 '17 at 08:29
  • Thanks @MagnusEriksson for your comment. I can see that the parser will clean up the CSS code but what I cant see is where you can create a multi dimensional array as per the output I need. Currently looking at https://github.com/sabberworm/PHP-CSS-Parser – deanhodges Jul 14 '17 at 08:53
  • That's just one parser. When I Googled "parse css with php" I found multiple libraries. – M. Eriksson Jul 14 '17 at 09:00

1 Answers1

0

UPDATE! I have found a solution which someone has modified the code originally added above. Break a CSS file into an array with PHP

Not 100% perfect (recommend using a parser) but this works for my quick tests or proof of concept for now.

deanhodges
  • 79
  • 1
  • 12