2010-08-11 68 views
0

我想用preg_replace替換「* @license until */」與「testing」。
我該怎麼做?
我的文字是下面的一個:preg_replace特定模式

/* 
* @copyright 
* @license 
* 
*/ 

我希望大家有正確地理解我的問題。

回答

0

好吧,這不是太難。所有你需要做的就是使用s修飾符(PCRE_DOT_ALL,這使得.在正則表達式匹配新行):

$regex = '#\\*\\s*@license.*?\\*/'#s'; 
$string = preg_replace($regex, '*/', $string); 

這應該爲你工作(注意,未經測試)...

2

這裏是你想要做什麼(在多行模式下運行)一個正則表達式

 
^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+ 

它被刪除線的部分相匹配:

 
/* 
* @copyright 

            
 
  
             * @license 
*
            
  
*/ 

說明:

 
^    ~ start-of-string 
\s*   ~ any number of white space 
\*    ~ a literal star 
\s*   ~ any number of white space 
@license  ~ the string "@license" 
(?:   ~ non-capturing group 
    (?!   ~ negative look ahead (a position not followed by...): 
    \s*  ~  any number of white space 
    \*   ~  a literal star 
    /  ~  a slash 
)   ~ end lookahead (this makes it stop before the end-of-comment) 
    [\s\S]  ~ match any single character 
)+    ~ end group, repeat as often as possible 

注意,正則表達式還必須根據PHP字符串規則根據preg_replace()規則進行轉義。

編輯:如果你喜歡它 - 使絕對確保,真的有結束註釋的標記以下匹配的文本,正則表達式可以展開如下:

 
^\s*\*\s*@license(?:(?!\s*\*/)[\s\S])+(?=\s*\*/) 
             ↑   positve look ahead for 
             +-----------an end-of-comment marker 
+0

非常有幫助方法來解釋正則表達式的語法,thx – 2013-01-23 10:37:09