开发者

How to parse bbcodes safely?

I'm trying to parse BBcodes in php but i don't think my code is safe at all.

$Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","<span style=\"color: $1\">$2</span>",$Text); 

I think you can pass an injection like this and it will work:

[color=<script>alert('gotcha');</script>]...[/color]

How to improve my regex to only capture the two standar color formats:

[color=r开发者_如何转开发ed]...[/color] OR [color=#FF0000]...[/color]

Thanks


PHP actually has built-in support for bbcode (though you'll need to install a PECL extension).

Alternatively, there is a PEAR library HTML_BBCodeParser that you can use.

I would recommend using one of the above solutions instead of writing your own as they have been community tested.


(\[color=((([a-zA-Z])+)|(\#[A-F0-9]{1,6})))

I think that's the idea, my regex is a little rusty (sorry).


If you do want to write your own bbcode parser, it's best to take some time to write a decent Recursive descent parser for it.

This because you must be sure that the bbcode is properly formatted and nested, having a random in your code can break the layout. You must take care to remove any javascript:// protocol identifiers in the links. And take take to only go over a string once to avoid double encoding ([b[b]bold me[/b]]me too[/b]). The list goes on and is beyond simple regexes to get completely right.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜