I'm parsing the BBCode using the regex in order to replace it into the HTML. I'm stuck right now because of the [code] tags parsing.

Basically, when you do [code][b]this is bb[/b] [u]code in[/u] [i]code[/i][/code] it shouldnt replace the [b], [u], [i] and similar tags that are INSIDE of the [code] tag.

Unfortunately, using the preg_replace:

$this->_text = preg_replace('/\[i](.+?)\[\/i]/i', '<em>\1</em>', $this->_text);
$this->_text = preg_replace('/\[code](.+?)\[\/code]]/i', '<code>\1</code>', $this->_text);

will cause replacing them all, and the code inside of the [code] tag will become HTML formated.

Is there any work-around for this? I need ideas. I was thinking about escaping the [, ] brackets characters in [code] before parsing the rest, but this idea sound silly.

有帮助吗?

解决方案

If you are going to parse from the exterior in, you need something like this for your code tag

(?:\[code])(.*)(?=(?:\[\/code]))

But as other have mentioned, you should be very careful with you do with this because you can not guarantee what is coming to you, it may be malformed and then you will end up with a mess of tags or even an incomplete mixture of parsed and unparsed bbcodes.

Even the code that i just wrote will fail if you have two [/code][/code].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top