我一直在尝试编写一个正则表达式,当它在一个打开和关闭的大括号('{','}')之间时,会删除分号(';')后面的空格。我已经到了某个地方,但还是没能把它拉下来。这就是我所拥有的:
<?php
$output = '@import url("/home/style/nav.css");
body{color:#777;
background:#222 url("/home/style/nav.css") top center no-repeat;
line-height:23px;
font-family:Arial,Times,serif;
font-size:13px}'
$output = preg_replace("#({.*;) \s* (.*[^;]})#x", "$1$2", $output);
?>
$输出应如下所示。另外,请注意字符串中的第一个分号后面仍然是空格,应该是这样。
<?php
$output = '@import url("/home/style/nav.css");
body{color:#777;background:#222 url("/home/style/nav.css") top center no-repeat;line-height:23px;font-family:Arial,Times,serif;font-size:13px}';
?>
谢谢!提前给任何愿意试一试的人。
答案 0 :(得分:1)
正则表达式对于这项工作来说是一个糟糕的工具,因为CSS不是regular language。如您所知,您在属性值中遇到了空白区域。正则表达不理解这种情况。
我假设您正在尝试缩小CSS。有工具可以做到这一点。我建议使用那些。要么是这个,要么得到一个解析CSS的库,并且可以用最小的空格输出它。
如果您坚持沿着正则表达式路线走,可以尝试Stunningly Simple CSS Minifier。
答案 1 :(得分:0)
你需要的是首先找到匹配({}之间的字符串),然后对其进行操作。函数preg_replace_callback()应该为您解决问题:
function replace_spaces($str){
$output = preg_replace('/(;[[:space:]]+)/s', ';', $str[0]);
return $output;
}
$output = '@import url("/home/style/nav.css");
body{color:#777;
background:#222 url("/home/style/nav.css") top center no-repeat;
line-height:23px;
font-family:Arial,Times,serif;
font-size:13px}';
$out = preg_replace_callback("/{(.*)}/s", 'replace_spaces', $output);
您可能需要针对多个匹配进行调整。