且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP将CSS文件分解为数组

更新时间:2022-05-26 05:53:08

这应该做到:

<?php

$css = <<<CSS
#selector { display:block; width:100px; }
#selector a { float:left; text-decoration:none }
CSS;

//
function BreakCSS($css)
{

    $results = array();

    preg_match_all('/(.+?)\s?\{\s?(.+?)\s?\}/', $css, $matches);
    foreach($matches[0] AS $i=>$original)
        foreach(explode(';', $matches[2][$i]) AS $attr)
            if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal
            {
                list($name, $value) = explode(':', $attr);
                $results[$matches[1][$i]][trim($name)] = trim($value);
            }
    return $results;
}
var_dump(BreakCSS($css));

快速说明:regexp简单而无聊.它仅匹配所有任何内容,可能的空间,大括号,可能的空间,任何东西,大括号".从那里开始,第一个匹配项是选择器,第二个匹配项是属性列表.用分号隔开,剩下键/值对.里面有一些trim()可以消除空格,就是这样.

Quick Explanation: The regexp is simple and boring. It just matches all "anything, possible space, curly bracket, possible space, anything, close curly bracket". From there, the first match is the selector, the second match is the attribute list. Split that by semicolons, and you're left with key/value pairs. Some trim()'s in there to get rid of whitespace, and that's about it.

我猜测您的下一个***选择可能是用逗号将选择器炸开,以便您可以合并适用于同一事物的属性,等等,但我会为您保存. :)

I'm guessing that your next best bet would probably be to explode the selector by a comma so that you can consolidate attributes that apply to the same thing etc., but I'll save that for you. :)

如上所述,一个真正的语法解析器会更实用...但是,如果您假设格式正确的CSS,那么除了最简单的任何内容"之外,您没有理由要做任何事情. .确实取决于您要执行的操作.

As mentioned above, a real grammar parser would be more practical... but if you're assuming well-formed CSS, there's no reason why you need to do anything beyond the simplest of "anything { anything }". Depends on what you want to do with it, really.