【问题标题】:php - split CSS into a multi-dimensional arrayphp - 将 CSS 拆分为多维数组
【发布时间】:2017-12-19 06:30:03
【问题描述】:

我需要一些帮助来从 CSS 创建一个多维数组。例如:

$css = "body { font-weight:40px; color:#444; } #wrapper { width: 500px; }";

我确实有来自Split CSS inside the {} to array of key/value pairs 的以下代码,但这也不能用于选择器

function BreakCSS($CSS) {
$results = array();

foreach(explode(';', $CSS) AS $attr)
    if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal
    {
        list($name, $value) = explode(':', $attr);
        $results[trim($name)] = trim($value);
    }
return $results;

}

我不是这种编码方面的专家。理想情况下,我想:

array(
    'body' => array (
        array(
            'font-weight',
            '40',
            'px'
        ),
        array(
            'color',
            '#444',
            ''
        )
    )
)

此外,有没有办法检查 !important 是否已添加到末尾?

提前致谢!

【问题讨论】:

  • 那我得问他们在你所指的帖子中所做的同样的事情,为什么不使用已经构建的解析器?
  • 感谢@MagnusEriksson 的评论。我可以看到解析器将清理 CSS 代码,但我看不到您可以根据我需要的输出创建多维数组的位置。目前正在查看github.com/sabberworm/PHP-CSS-Parser
  • 这只是一个解析器。当我用谷歌搜索“用 php 解析 css”时,我发现了多个库。

标签: php css arrays multidimensional-array


【解决方案1】:

更新!我找到了一个解决方案,有人修改了上面最初添加的代码。 Break a CSS file into an array with PHP

不是 100% 完美(建议使用解析器),但这适用于我现在的快速测试或概念验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多