代码之家  ›  专栏  ›  技术社区  ›  ak85

使用正则表达式将类添加到css的每一行

  •  2
  • ak85  · 技术社区  · 12 年前

    我想在css的每一行的开头添加一个类

    我想要

    .more {
        padding: 5px 10px 0;
    }
    
    #fbook {
        display: inline;
        float: left;
        margin: 0 0 0 4px;
        width: 320px;
    }
    

    看起来像

    .test .more {
        padding: 5px 10px 0;
    }
    
    .test #fbook {
        display: inline;
        float: left;
        margin: 0 0 0 4px;
        width: 320px;
    }
    

    像这样的东西。

    ^([A-Za-z0-9]+)$
    

    如果我的css看起来像这样会起作用

    more
    {
        padding: 5px 10px 0;
    }
    
    fbook
    {
        display: inline;
        float: left;
        margin: 0 0 0 4px;
        width: 320px;
    }
    

    但我似乎什么时候都找不到。#{

    2 回复  |  直到 12 年前
        1
  •  2
  •   Cylian Joey    12 年前

    试试这个

    $result = preg_replace('/(?i)^([.#a-z]+\{)$/m', '.test $1', $subject);
    

    解释

    "
    (?im)         # Match the remainder of the regex with the options: case insensitive (i); ^ and \$ match at line breaks (m)
    ^             # Assert position at the beginning of a line (at beginning of the string or after a line break character)
    (             # Match the regular expression below and capture its match into backreference number 1
       [.#a-z]       # Match a single character present in the list below
                        # One of the characters “.#”
                        # A character in the range between “a” and “z”
          +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
       \{            # Match the character “{” literally
    )
    \$             # Assert position at the end of a line (at the end of the string or before a line break character)
    "
    
        2
  •  1
  •   Kobi    12 年前

    你可以使用现代工具 LESS 。只需取下您的代码,然后用 .test{ } 以下为:

    .test {
        .more {
            padding: 5px 10px 0;
        }
    
        #fbook {
            display: inline;
            float: left;
            margin: 0 0 0 4px;
            width: 320px;
        }
    }
    

    如果您只需要一次,您可以在线完成: http://leafo.net/lessphp/#demo
    如果你想不时地这样做,那么你可以使用的许多语言的库更少,还有客户端JavaScript选项。