使用preg_replace获取和替换属性


Fetch and Replace properties with preg_replace

我想为这里的所有属性添加选项卡,但我不知道如何隔离属性$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;
    }
*/

你可以试试:

$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