您只能使用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]
(* 量词在这里是明确所有格的,因为即使字符类不包括[
and 后跟一个字面量[
,自动占有也不会发生,因为\K
介于字符类和字面量之间[
。但是,该模式也适用于一个“正常”量词。您可以在此处找到有关所有格量词和有关自动占有的更多信息。)