使用preg_replace获取和替换属性

时间:2014-03-20 13:16:22

标签: php css function preg-replace eof

我想在此处为所有属性添加制表符,但我不知道如何隔离属性$ 1在这里不起作用。

小调整会使这个工作......

谢谢!

$css = <<<EOF

body {
padding : 0px;
margin: 0px;
line-height: 10px;
}

p {
z-index: 9;
font-size: 10px;
}

EOF;


echo preg_replace('#({)(.*?)(})#', '\t$1' , $css);

/*

I'm expecting to get all properties with TAB :

    body {
         padding : 0px;
         margin: 0px;
         line-height: 10px;
    }

    p {
           z-index: 9;
           font-size: 10px;
    }
*/

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

$pattern = '~(?:{|\G(?!\A))\s*?;?\s*\K[^;}]+~';
echo preg_replace($pattern, "\t$0" , $css);

模式细节:

(?:          # possible beginings of the match
    {        # a curly bracket
  |          # OR
    \G(?!\A) # the end of a precedent match
)
\s*?;?\s*    # spaces (after the curly bracket) or ending ; of a property 
\K           # resets all the begining from match result
[^;}]+       # all that is not a closing curly bracket or a semi-colon