preg_replace掉CSS注释? [英] preg_replace out CSS comments?

查看:79
本文介绍了preg_replace掉CSS注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个快速的preg_replace,以从CSS中删除注释. CSS注释通常具有以下语法:

I'm writing a quick preg_replace to strip comments from CSS. CSS comments usually have this syntax:

/* Development Classes*/
/* Un-comment me for easy testing
  (will make it simpler to see errors) */

所以我试图杀死/*和*/之间的所有内容,像这样:

So I'm trying to kill everything between /* and */, like so:

$pattern = "#/\*[^(\*/)]*\*/#";
$replace = "";
$v = preg_replace($pattern, $replace, $v);

没有骰子!斜线似乎令人窒息,因为如果我将/s从模式中删除,则可以删除注释文本.我尝试了一些更简单的模式来查看是否可以丢失斜线,但是它们会返回原始字符串不变:

No dice! It seems to be choking on the forward slashes, because I can get it to remove the text of comments if I take the /s out of the pattern. I tried some simpler patterns to see if I could just lose the slashes, but they return the original string unchanged:

$pattern = "#/#";
$pattern = "/\//";

关于为什么我似乎无法匹配这些斜线的任何想法?谢谢!

Any ideas on why I can't seem to match those slashes? Thanks!

推荐答案

这是一个解决方案:

$regex = array(
"`^([\t\s]+)`ism"=>'',
"`^\/\*(.+?)\*\/`ism"=>"",
"`([\n\A;]+)\/\*(.+?)\*\/`ism"=>"$1",
"`([\n\A;\s]+)//(.+?)[\n\r]`ism"=>"$1\n",
"`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n"
);
$buffer = preg_replace(array_keys($regex),$regex,$buffer);

来自Samstyle PHP框架中的脚本/样式表预处理器

Taken from the Script/Stylesheet Pre-Processor in Samstyle PHP Framework

请参阅: http://code. google.com/p/samstyle-php-framework/source/browse/trunk/sp.php

csstest.php:

csstest.php:

<?php

$buffer = file_get_contents('test.css');

$regex = array(
"`^([\t\s]+)`ism"=>'',
"`^\/\*(.+?)\*\/`ism"=>"",
"`([\n\A;]+)\/\*(.+?)\*\/`ism"=>"$1",
"`([\n\A;\s]+)//(.+?)[\n\r]`ism"=>"$1\n",
"`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n"
);
$buffer = preg_replace(array_keys($regex),$regex,$buffer);
echo $buffer;

?>

test.css:

/* testing to remove this */
.test{}

csstest.php的输出:

Output of csstest.php:

.test{}

这篇关于preg_replace掉CSS注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆