views:

75

answers:

3

Hi,

I'm creating a CSS generator in PHP which uses CSSX (yep, they are my idea) files (with a special syntax). One feature is 'short comments':

body
{
    font-family: Georgia; //I really like this font!
}

Now I want to replace this comment with a /* ... */ comment, so the output is like this:

body
{
    font-family: Georgia; /*I really like this font!*/
}

How can I do this? Thanks,

P.S. The complete CSSX file is read into one string variable.
P.P.S This q is answered. To fix the url('//server/etc.cssx') problem, use this:

$file =  preg_replace('~[^"\'\(]//([^\r\n]*)[^"\'\)]~', '/*$1*/', $file);
+5  A: 

A regexp should do the trick:

$str = preg_replace('_//(.*)$_m', '/*$1*/', $str);

This won't take into account quoted strings - if you're using something crazy like

background-image: url('//my-server/my.jpg');

then it's going to think that's a comment. If this is a problem then you're better off writing a proper parser.

Greg
Awesome it worked!
Time Machine
@Koning: they just specify the delimiter for the regular expression. You can use many characters, and `preg_replace` will assume the first one is the delimiter you want to use. The "standard" delimiter is `/`, but then you'd have to escape your `/`'s in the pattern.
jheddings
Hmmm, move the newline, and I think you're set:http://codepad.org/uNV7jQmb
Tchalvak
Okay I understand. I thought only / was available as a delimiter.
Time Machine
I fixed the problem with the url(). Just use this: <code>$file = preg_replace('~[^"\'\(]//([^\r\n]*)[^"\'\)]~', '/*$1*/', $file);</code>
Time Machine
+3  A: 
<? preg_replace('#//(.*)$#', '/*$1*/', $cssx); ?>
jheddings
You were 26 seconds to late but I'll upvote it ^_^
Time Machine
@Koning: I just can't compete with Greg's lightning fingers... tnx
jheddings
+1  A: 

Greg's expression has two problems: first, 'm' and '$' are superfluous, second it doesn't handle carriage returns correctly (in case your system uses them).

A better expression appears to be

 preg_replace('~//([^\r\n]*)~', '/*$1*/', $str);
stereofrog
Well, it's really important it'll work on OSX, Linux and Windows since I'll release the source.
Time Machine