簡體   English   中英

PHP Regex刪除特定的CSS Comment

[英]PHP Regex to remove specific CSS Comment

我想在下面的php匹配條件中編寫正則表達式:

   /* 
    Remove this comment line 1
    Remove this comment line 2
   */
   .class1
   {
      background:#CCC url(images/bg.png);
   }

   .class2
   {
      color: #FFF;
      background:#666 url(images/bg.png); /* DON'T remove this comment */
   }

   /* Remove this comment */
   .class3
   {
      margin:2px;
      color:#999;
      background:#FFF; /* DON'T Remove this comment */
   }

    ...etc
    ...etc

請任何人在PHP中給我一個正則表達式。 謝謝。

不適用於多行評論

/*
 * Lorem ipsum
 */

這個人做的工作

$regex = "!/\*[^*]*\*+([^/][^*]*\*+)*/!";
$newstr = preg_replace($regex,"",$str);
echo $newstr;

http://codepad.org/xRb2Gdhy

在此處找到: http//www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php

如果規則是你要刪除行上沒有其他代碼的所有注釋,那么這樣的事情應該有效:

/^(\s*\/\*.*?\*\/\s*)$/m

'm'選項使^和$匹配一行的開頭和結尾。 您是否希望評論針對多行進行?

編輯:

我很確定這符合要求:

/(^|\n)\s*\/\*.*?\*\/\s*/s

你明白它在做什么嗎?

鍵盤: http//codepad.org/aMvQuJSZ

支持多線:

/* Remove this comment 
multi-lane style 1*/

/* Remove this comment 
multi-lane style 2
*/

/* Remove this comment */

正則表達式說明:

^            Start of line
\s*          only contains whitespace
\/\*         continue with /*
[^(\*\/)]*   unlimited number of character except */ includes newline
\*\/         continue with */
m            pattern modifier (makes ^ start of line, $ end of line

示例php代碼:

$regex = "/^\s*\/\*[^(\*\/)]*\*\//m";
$newstr = preg_replace($regex,"",$str);
echo $newstr;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM