Explode or Similar does not break enclosed delimiters

1

I'm developing a CSS parser, but when it arrives in a block like this:

    height: 100%;
    background-image: url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7");
    display: block;

First I have to normalize with:

$rules = str_replace(array("\n","\r"), array('',''), $rules);

// Que me retorna:
// height: 100%; background-image: url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"); display: block;

(since files may come with rules on the same line)

And when applying:

$rules = explode(';',$rules);

Explode break in ; within string "... gif ; base64 ..."

I was able to "solve" by applying str_replace from ;base64 to -base64 and then at the time of rendering css, replacing -base64 with ;base64 . Gambiarra level 9000

This obviously limits to just this situation, and I need a broader solution, such as not breaking if ; is within " , ' , ( or )

I have tried str_getcsv and it does not work ...

Pastebin full function.

    
asked by anonymous 12.09.2014 / 18:59

1 answer

1

I have achieved a broader solution using a REGEX that replaces all ; that are enclosed within ( ) by: [ENCLOSED_DELIMITER] , and after breaking with explode , replaces ;

$teste = 'height: 100px; background: url("data:image/gif;base64;//PRIMEIRO;"); display: block; background: url(\'data:image/gif;base64,//SEGUNDO\'); display: block; background: url(data:image/gif;base64,//TERCEIRO);';

$teste = preg_replace_callback(
            '/\([^\)]*\)/',
            function ($matches) {
                return str_replace(';', '[ENCLOSED_DELIMITER]', $matches[0]);
            },
            $teste);

$teste = explode(';', $teste);

foreach($teste as &$v) $v = str_replace('[ENCLOSED_DELIMITER]', ';', $v);

print_r(array_filter($teste));

// Retorno:

Array
(
    [0] => height: 100px
    [1] =>  background: url("data:image/gif;base64;//PRIMEIRO;")
    [2] =>  display: block
    [3] =>  background: url('data:image/gif;base64,//SEGUNDO')
    [4] =>  display: block
    [5] =>  background: url(data:image/gif;base64,//TERCEIRO)
)

It is a game, but at least it is broader.

If anyone knows of other possibilities that may contain ; in CSS rules, please comment below.

Follow the pastebin of the full parser for those interested.

    
12.09.2014 / 21:29