2017-07-14 113 views
0

我需要一些帮助从CSS创建多维数组。例如:php - 将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', 
      '' 
     ) 
    ) 
) 

此外,有没有一种方法来检查!重要是否已添加到最后?

在此先感谢!

+0

然后,我必须问他们在你所指的文章中所做的相同的事情,为什么不使用已经构建的解析器? –

+0

感谢@MagnusEriksson的评论。我可以看到解析器将清理CSS代码,但是我无法看到的是根据需要输出创建多维数组的位置。目前正在查看https://github.com/sabberworm/PHP-CSS-Parser – deanhodges

+0

这只是一个解析器。当我谷歌搜索“用PHP解析css”时,我发现了多个库。 –

回答

0

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

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