本文介绍了PHP简单的CSS串分析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一些CSS code,如:

I need to parse some CSS code like:

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来做到这一点。我可以看到这个轻松地通过正则表达式进行(不好,容易对那些知道它,不像我自己:-))。

  • 我需要的结果数组是正常化,不应该有记号之间有任何尾随空格,即使他们在源。

  • 毫无价值的CSS令牌应该包括阵列,因为只有一个关键英寸(见--crap)

  • 行情(和值一般)应保持原样,除了额外的格式(空格,制表符);经由装饰容易地除去()或通过相关的规则表达式开关。

  • 请不就是在这一点上,我专门的不需要一个完整的CSS解析器,也就是说,没有必要解析块( {...} )或选择器( a.myclass#身份识别码)。

  • 哦,考虑到我会放这个东西在一个数组,这是完全确定的,如果最后一个项目(颜色:红色; )的完全覆盖的原项目(颜色:黑色; )。

    • I need to do this via PHP. I can see this done easily via regexp (well, easy to those that know it, unlike myself :-) ).
    • I need the resulting array to be "normalized", there should not be any trailing spaces between tokens, even if they were in the source.
    • Valueless css tokens should be included in the array as a key only. (see --crap)
    • Quotes (and values in general) should remain as is, except for extra formatting (spaces, tabs); easily removed via trim() or via the relevant regexp switch.
    • Please not that at this point, I specifically do not need a full CSS parser, ie, there is no need to parse blocks ( {...} ) or selectors ( a.myclass#myid ).
    • Oh, and considering I'll be putting this stuff in an array, it is perfectly ok if the last items ( color:red; ) completely override the original items ( color:black; ).
    • 推荐答案

      下面是一个简单的版本:

      Here's a simple version:

          $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
      }
      

      不与任何测试,除了源数据,所以我敢肯定,它有缺陷。可能足以让你开始。

      Not tested with anything except your source data, so I'm sure it has flaws. Might be enough to get you started.

      这篇关于PHP简单的CSS串分析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:54