2014-09-06 117 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); 
相关问题