views:

208

answers:

2

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.

+1  A: 

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.

cletus
A: 

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.

pinaki
Thank you very much this is exactly what I needed.
roydukkey
might consider puting an upvote ;)...
pinaki