开发者

PHP RegEx: How to Stripe Whitespace Between Two Strings

I have been trying to write a regex that will remove whitespace following a semicolon (';') when it is between both an open and close curly brace ('{','}'). I've gotten somewhere but haven't been able to pull it off. Here what I've got:

<?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);
?>

The the $output should be as follows. Also, notice that the first semicolon in the string still is followed by whitespace, as it should be.

<?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}';
?>

Thanks! In advance to anyone willing to give it a shot.


Regex is a bad tool for this job because CSS is not a regular language. You come across white space in property values as you're aware. Regexes don't understand such contexts.

I assume you're trying to minify your CSS. There are tools for that. I'd suggest using those. Either that or get a library that parses CSS and can output it with minimal white space.

If you insist on going down the regex route, perhaps try Stunningly Simple CSS Minifier.


What you need is to first find the match (string between the {}) and then operate on it. The function preg_replace_callback() should do the trick for you:

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);

You might need to tweak this for multiple matches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜