2011-11-24 70 views
0

我想要寫在下面的PHP匹配條件的正則表達式:PHP正則表達式來移除特定CSS評論

/* 
    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中的正則表達式。謝謝。

+0

你爲什麼不刪除所有評論? – meotimdihia

回答

1

如果規則是要刪除所有的意見,其中有上線沒有其他的代碼,然後這樣的事情應該工作:

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

的「M」選項使得^和$開頭匹配並結束一行。你是否期望評論可以運行多行?

編輯:

我敢肯定,這符合該法案:

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

你明白它在做什麼?

+0

/\n\s*\/\*.*?\*\/\s*\n/s – Godwin

+0

其實:/(^ | \ n)\ s * \/\ *。*?\ * \/\ s *(\ n | $)/ s – Godwin

+0

'/ \ n \ s * \/*。*?* \/\ s * \ n/s'和'/(^ | \ n)\ s * \/* * * * \/\ s *(\ n | $)/ s'不適合我,@戈德溫。使用preg_replace時產生一些錯誤。 –

0

鍵盤:http://codepad.org/aMvQuJSZ

支持多行:

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

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

/* Remove this comment */ 

Regex的說明:

^   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; 
+0

謝謝,它在一行評論中的工作,多行評論怎麼樣。像:'/ ****** Line1 line2 line3 ****** /' –

+0

多車道支持添加示例鏈接:http://codepad.org/Tknf440o –

+0

好的,謝謝。是工作 。 –