Reputation: 2147
I'm currently writing a function in PHP to translate BBCodes for a forum engine.
Now I wanted to add a [code]
-tag and I created the following function:
$txt = preg_replace('#\[code\](.*)\[(.*)\[/code\]#isU', "<div class=\"bb_uncode\">$1[$2</div>", $txt);
(Side note: [
equals [)
This works very well if there's only one [
inside the [code]-tags, but it ignores every further one.
Is there a possiblity to apply this search pattern on every other brackets, too?
Upvotes: 1
Views: 134
Reputation: 89567
You can do it with preg_replace only:
$txt = preg_replace('~(?:\[code]|\G(?!^))[^[]*+\K\[(?!/code])~i',
'[', $txt);
Pattern details:
(?: # 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]
(* the quantifier is explicitly possessive here because, even if the character class excludes the [
and is followed by a literal [
, the auto-possessification can't occur since the \K
is between the character class and the literal [
. However, the pattern works too with a "normal" quantifier. You can find more informations about possessive quantifiers here and about auto-possessification here.)
Upvotes: 0
Reputation: 781096
Do this with preg_replace_callback()
:
$txt = preg_replace_callback('#\[code\](.*)\[/code\]#isU', function($match) {
return "<div class=\"bb_uncode\">" .
str_replace('[', '[', $match[1]) .
"</div>");
}, $txt);
Upvotes: 1