Search code examples
phpregexbbcode

Regex & BBCode - Perfecting Nested Quote


I'm working on some BBcode for my website.

I've managed to get most of the codes working perfectly, however the [QUOTE] tag is giving me some grief.

When I get something like this:

[QUOTE=1]
[QUOTE=2]
This is a quote from someone else
[/QUOTE]
This is someone else quoting someone else
[/QUOTE]

It will return:

> 1 said:  [QUOTE=2]This is a quote from
> someone else

This is someone else quoting someone else[/QUOTE]

So what is happening is the [/quote] from the nested quote is closing the quote block.

The Regex I am using is:

"[quote=(.*?)\](.*?)\[/quote\]'is"

How can I make it so nested Quotes will appear properly?

Thank you.


Solution

  • You could construct recursive regular expression (available since libpcre-3.0 according to their changelog):

    \[quote=(.*?)\](((?R)|.)*?)\[\/quote\]
    

    But it would be better if you follow @codeka advice.

    Update: (?R) here means «insert the whole regular expression in place where (?R) occurs». So a(?R)?b is equivalent (if you forget about capturing groups) to a(a(?-1)?b)?b which is equivalent to a(a(a(?-1)?b)?b)?b and so on. Instead of (?R) you can use (?N), (?+N), (?-N) and (?&a) which means «substitute with N'th capturing group», «substitute with N'th next capturing group», «substitute with N'th previous capturing group» and «substitute with capturing group named «a»».