2014-09-06 134 views
0

我很努力地使用regEx,但無法讓它正常工作。 我已經嘗試使用: SO questiononline tool需要PHP regEx幫助/ * <##></##> */

$text = preg_replace("%/\*<##>(?:(?!\*/).)</##>*\*/%s", "new", $text); 

但沒有任何工程。 我的輸入字符串是:

$input = "something /*<##>old or something else</##>*/ something other"; 

和預期的結果是:

something /*<##>new</##>*/ something other 
+0

你沒有一個量詞先行掩蓋的''全匹配()。因此它只會在您的評論中接受一個字符的字符串。也可以用'new'替換,不會重新實例化'comment *標記。 – mario 2014-09-06 21:26:44

回答

3

我看到,這裏指出兩個問題,你有沒有捕獲組來替換你更換電話和內部的分隔標記你Negative Lookahead語法缺少repetition operator

$text = preg_replace('%(/\*<##>)(?:(?!\*/).)*(</##>*\*/)%s', '$1new$2', $text); 

雖然,你可以因爲你使用的是s(DOTALL)修飾符.*?取代超前。

$text = preg_replace('%(/\*<##>).*?(</##>*\*/)%s', '$1new$2', $text); 

或者考慮使用週轉的組合來做到這一點,而不捕獲組。

$text = preg_replace('%/\*<##>\K.*?(?=</##>\*/)%s', 'new', $text); 
0

測試:

$input = "something /*<##>old or something else</##>*/ something other"; 

echo preg_replace('%(/\*<##>)(.*)(</##>\*/)%', '$1new$3', $input); 
相關問題