Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a solution:

$regex = array(
"`^([s]+)`ism"=>'',
"`^/*(.+?)*/`ism"=>"",
"`([
A;]+)/*(.+?)*/`ism"=>"$1",
"`([
A;s]+)//(.+?)[

]`ism"=>"$1
",
"`(^[
]*|[
]+)[s]*[
]+`ism"=>"
"
);
$buffer = preg_replace(array_keys($regex),$regex,$buffer);

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

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

csstest.php:

<?php

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

$regex = array(
"`^([s]+)`ism"=>'',
"`^/*(.+?)*/`ism"=>"",
"`([
A;]+)/*(.+?)*/`ism"=>"$1",
"`([
A;s]+)//(.+?)[

]`ism"=>"$1
",
"`(^[
]*|[
]+)[s]*[
]+`ism"=>"
"
);
$buffer = preg_replace(array_keys($regex),$regex,$buffer);
echo $buffer;

?>

test.css:

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

Output of csstest.php:

.test{}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...