PHP简单的CSS字符串解析器

时间:2010-09-15 06:30:59

标签: php css regex arrays parsing

我需要解析一些CSS代码,如:

color: black;
font-family:"Courier New";
background:url('test.png');
color: red;
--crap;

分为:

array (
    'color'=>'red',
    'font-family'=>'"Courier New"',
    'background'=>'url(\'test.png\')',
    '--crap'=>''
)
  • 我需要通过PHP来做到这一点。我可以通过regexp很容易地看到这一点(对于那些知道它的人来说很容易,不像我自己:-))。
  • 我需要将结果数组“标准化”,标记之间不应有任何尾随空格,即使它们位于源代码中。
  • 无值css标记应仅作为键包含在数组中。 (见--crap)
  • 除了额外的格式(空格,制表符)外,引号(和一般值)应保持不变;通过trim()或通过相关的正则表达式开关轻松删除。
  • 请注意,此时,我特别不需要完整的CSS解析器,即无需解析块({...})或选择器({{1} })。
  • 哦,考虑到我将把这些东西放在一个数组中,如果最后一项(a.myclass#myid完全覆盖原始项目({{1} })。

4 个答案:

答案 0 :(得分:2)

这是一个简单的版本:

    $a = array();
    preg_match_all('/^\s*([^:]+)(:\s*(.+))?;\s*$/m', $css, $matches, PREG_SET_ORDER);
    foreach ($matches as $match)
            $a[$match[1]] = isset($match[3]) ? $match[3] : null;

示例输出:

array(4) {
  ["color"]=>
  string(3) "red"
  ["font-family"]=>
  string(13) ""Courier New""
  ["background"]=>
  string(15) "url('test.png')"
  ["--crap"]=>
  NULL
}

除了您的源数据以外没有测试任何东西,所以我确定它有缺陷。可能足以让你入门。

答案 1 :(得分:0)

您可以尝试:

$result = array();
if(preg_match_all('/\s*([-\w]+)\s*:?\s*(.*?)\s*;/m',$input,$m))
        var_dump($m);
        // $m[1] contains all the properties
        // $m[2] contains their respective values.
        for($i=0;$i<count($m[1]);$i++) {
                $result[$m[1][$i]] = $m[2][$i];
        }
}

答案 2 :(得分:0)

我发现这几周后看起来很有趣。

http://websvn.atrc.utoronto.ca/wsvn/filedetails.php?repname=atutor&path=/trunk/docs/include/classes/cssparser.php

示例:

$Parser = new cssparser();
$Results = $Parser->ParseStr("color: black;font-family:"CourierNew";background:url('test.png');color: red;--crap;");

答案 3 :(得分:0)

为什么不看看CSSTidy

相关问题