Question

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&#91;$2</div>", $txt); 

(Side note: &#91; 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?

Was it helpful?

Solution

Do this with preg_replace_callback():

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

OTHER TIPS

You can do it with preg_replace only:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top