K
K
Kanaris2015-10-21 20:24:09
PHP
Kanaris, 2015-10-21 20:24:09

How to parse CSS with php?

You need to turn the string of css rules (i.e. the value of the attribute style="") into an array of the format ['rule'=>'value'].
explode(';',$style) don't suggest because:
background-image: url("data:image/gif;base64,...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-10-21
@Kanaris

https://github.com/sabberworm/PHP-CSS-Parser
In general, the task can be implemented in 20-30 lines, as already mentioned, by writing your own primitive character-by-character parser (with regular expressions). But it’s necessary to write this ... and it’s not a fact that we will cover all cases.
but if you're bored, here's a sketch of an idea, crooked and not pretty...

<?php

$styles = "background : 'te;st'; font-size: 12px";

parse($styles); // ["background", "'te;st'", "font-size", "12px"]

function parse($rawStyles) {
    $styles = rtrim($rawStyles, ';') . ';';
    $isInString = false;
    $offset = 0;
    $chunks = [];
    $lastChunkOffset = 0;
    while(preg_match('/[:;\'\"]/', $styles, $matches, PREG_OFFSET_CAPTURE, $offset)) {
        $offset = $matches[0][1] + 1;
        $char = $matches[0][0];
        if ($isInString && !in_array($char, ['\'', '"'])) {
            continue;
        }
        if (in_array($char, ['\'', '"'])) {
            $isInString =  !$isInString;
            continue;
        }

        $chunks[] = trim(mb_substr($styles, $lastChunkOffset, $offset - $lastChunkOffset-1));

        $lastChunkOffset = $offset;
    }

    return $chunks;
}

I
Ivanq, 2015-10-21
@Ivanq

What adequate css parsers for php, js or jquery exist and which one to choose?
And a bunch more like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question