开发者

PHP: Replace CSS Property in Regex

开发者 https://www.devze.com 2023-03-31 16:02 出处:网络
I\'m trying to parse CSS with Regex and replace specific values in PHP. Currently I\'ve been able to parse the CSS files using the \"CSS Parser\" class found here.

I'm trying to parse CSS with Regex and replace specific values in PHP.

Currently I've been able to parse the CSS files using the "CSS Parser" class found here.

I've been able to create simple regex as I'm not too advanced, that doesn't account for quirks like spacing.

Example

.marked     p

Would not be parsed, so I had to scrap it.

Is there an available Regex that can be used in conjuncti开发者_JS百科on with preg_replace that can acheive this?


This pattern finds all the selectors and turns the rules into key-value arrays. It should work on wellformed CSS, otherwise some tweaking might need be done.

The idea is that in CSS there will not be anything but selectors between the brackets of rules. It searches for a string until it comes to a start-bracket and interprets that as a selector. So it basically searches for "not {", and when it has come to a { it knows it's found a selector. Because of this it might not properly handle @imports but that can be accounted for also.

The code is from my CSS Compiler and parser which has taken a lot of ideas from Andreas Lagerkvist

function callback($match)
{
    // Normalize whitespace from selector
    $selector = trim(preg_replace('/\s\s+/', ' ', $match[1]));

    // Turn the rules into key-value array
    $rules_str = str_replace(array('{', '}'), '', trim(preg_replace('/\s\s+/', ' ', $match[2])));
    $rules_pieces = explode(';', $rules_str);
    $rules = array();

    foreach ( $rules_pieces as $rule )
    {
        // No key-value pair?
        if ( ! strstr($rule, ':') ) continue;

        list($key, $value) = explode(':', trim($rule));
        $rules[$key] = trim($value);
    }

    // Do some stuff
    echo $selector . PHP_EOL;
}

$css = "
    body {
            font: foo; size: 1px; 
    }

    #foo .bar div {
            foo: bar;
            foooo: bar;
    }  

    #foo    .bar div { foo: bar; }
";

preg_replace_callback('/([^{;]+)(\{[^}]+\})/', 'callback', $css);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号