2017-07-14 135 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%完美(推薦使用解析器),但這適用於我現在的快速測試或概念驗證。