Skip parsing the BBCode inside the CODE tag

核能气质少年 提交于 2019-12-02 14:41:15

问题


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.


回答1:


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].



来源:https://stackoverflow.com/questions/21551385/skip-parsing-the-bbcode-inside-the-code-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!