2013-07-23 85 views
1

我目前正在用PHP编写一个函数来为论坛引擎翻译BBCodes。 现在我想添加一个[code] - 标签和我创建了以下功能:preg替换多个结果

$txt = preg_replace('#\[code\](.*)\[(.*)\[/code\]#isU', "<div class=\"bb_uncode\">$1&#91;$2</div>", $txt); 

(旁注:&#91;平等[)
这工作得很好,如果只有一个[的[代码中]标签都有效,但它会忽略每一个。
是否有可能将此搜索模式应用于每个其他括号?

回答

1

preg_replace_callback()这样做:

$txt = preg_replace('~(?>\[code]|\G(?<!^))[^[]*+\K\[(?!/code])~i', 
        '&#91;', $txt); 

模式的细节:

$txt = preg_replace_callback('#\[code\](.*)\[/code\]#isU', function($match) { 
    return "<div class=\"bb_uncode\">" . 
      str_replace('[', '&#91;', $match[1]) . 
      "</div>"); 
}, $txt); 
0

您可以了preg_replace只有做到这一点

(?>     # open a non capturing group (atomic *) 
    \[code]   # [code] 
|     # OR 
    \G    # contiguous to the last match 
    (?<!^)   # and not preceded by the begining of the string 
)     # close the non capturing group 
    [^[]*+   # 0 or more characters that are not a [ (possessive *) 
\K     # reset all that have been matched before 
\[     # a literal [ 
(?!/code])   # not followed by /code] 

(*量词是占有欲该组是原子的,以避免正则表达式e ngine录音回溯位置。所以,这个模式更高效。但是,该模式可以在没有这些功能的情况下替换(?>(?:并删除+*+。 您可以在此主题找到更多信息herehere。)