我目前正在用PHP编写一个函数,为论坛引擎翻译BBCodes。现在我想添加一个[code]
-标签,并创建了以下函数:
$txt = preg_replace('#'[code'](.*)'[(.*)'[/code']#isU', "<div class='"bb_uncode'">$1[$2</div>", $txt);
(旁注:[
等于[)
如果[code]-标记中只有一个[
,那么这种方法非常有效,但它会忽略每一个
是否有可能将这种搜索模式应用于其他方括号?
使用preg_replace_callback()
:执行此操作
$txt = preg_replace_callback('#'[code'](.*)'[/code']#isU', function($match) {
return "<div class='"bb_uncode'">" .
str_replace('[', '[', $match[1]) .
"</div>");
}, $txt);
只能使用preg_replace:
$txt = preg_replace('~(?:'[code]|'G(?!^))[^[]*+'K'[(?!/code])~i',
'[', $txt);
图案细节:
(?: # open a non-capturing group
'[code] # [code]
| # OR
'G # contiguous to the last match
(?!^) # and not at 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]) # negative lookahead: not followed by /code]
(*这里的量词是明确的所有格,因为即使字符类排除了[
,后面跟着文字[
,也不会发生自动所有格化,因为'K
位于字符类和文字[
之间。然而,这种模式也适用于"正常"量词。你可以在这里找到更多关于所有格量词的信息此处为自动占有。)