使用PHP将CSS文件分解为数组 [英] Break a CSS file into an array with PHP

查看:113
本文介绍了使用PHP将CSS文件分解为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用PHP将css文件分解成一个数组.

I wanted to break a css file into an array with PHP.

例如:

#selector{ display:block; width:100px; }
#selector a{ float:left; text-decoration:none; }

放入php数组...

Into a php array...

array(2) {
  ["#selector"] => array(2) {
    [0] => array(1) {
      ["display"] => string(5) "block"
    }
    [1] => array(1) {
      ["width"] => string(5) "100px"
    }
  }
  ["#selector a"] => array(2) {
    [0] => array(1) {
      ["float"] => string(4) "left"
    }
    [1] => array(1) {
      ["text-decoration"] => string(4) "none"
    }
  }
}

有什么想法吗?

哦:在这种情况下,我不担心格式不正确的CSS文件.只要不贪心,就不必防弹

Oh : Edit : I am not worried about ill formed CSS files in this instance. Doesn't ahve to be bulletproof as long as its not greedy

推荐答案

这应该做到:

<?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.

这篇关于使用PHP将CSS文件分解为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆