用PHP中的/ *注释* /替换//注释 [英] Replacing // comments with /* comments */ in PHP
问题描述
我正在用PHP创建一个CSS生成器,该生成器使用CSSX(是的,这是我的想法)文件(具有特殊的语法)。一种功能是简短评论:
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!*/
}
我该怎么做?谢谢,
P.S。完整的CSSX文件被读入一个字符串变量。
P.P.S回答此q。要解决url('// server / etc.cssx')问题,请使用以下方法:
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);
推荐答案
正则表达式可以解决问题:
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.
这篇关于用PHP中的/ *注释* /替换//注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!