Parsing CSS by regex

前端 未结 8 1754
时光说笑
时光说笑 2020-11-27 17:37

I\'m creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can\'t get it to

8条回答
  •  余生分开走
    2020-11-27 18:16

    I would recommend against using regex's to parse CSS - especially in single regex!

    If you insist on doing the parsing in regex's, split it up into sensible sections - use one regex to split all the body{..} blocks, then another to parse the color:rgb(1,2,3); attributes.

    If you are actually trying to write something "useful" (not trying to learn regular expressions), look for a prewritten CSS parser.

    I found this cssparser.php which seems to work very well:

    $cssp = new cssparser;
    $cssp -> ParseStr("body { background: #f00;font: 12px Arial; }");
    print_r($cssp->css);
    

    ..which outputs the following:

    Array
    (
        [body] => Array
            (
                [background] => #f00
                [font] => 12px arial
            )
    )
    

    The parser is pretty simple, so should be easy to work out what it's doing. Oh, I had to remove the lines that read if($this->html) {$this->Add("VAR", "");} (it seems to be a debugging thing that was left in)

    I've mirrored the script here, with the above changes in

提交回复
热议问题