Answer the question
In order to leave comments, you need to log in
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
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question