UBB code conversions - simple function with a sample set of UBB code tags

Bill

80.***.***.***
1,937 days ago

UBB code conversions - simple function with a sample set of UBB code tags

This is a function with a sample set of UBB-like code conversions, variations of which is often used in public chat and message boards in conjunction with a complete disallowment of publicly supplied HTML and JavaScript.

PHP code:

function ubbconvert($a){
$a=str_replace("[hr]","<hr size=\"1\" noshade>",$a);
$a=preg_replace("/\[b\](.*?)\[\/b\]/si","<b>\\1</b>",$a);
$a=preg_replace("/\[i\](.*?)\[\/i\]/si","<i>\\1</i>",$a);
$a=preg_replace("/\[u\](.*?)\[\/u\]/si","<u>\\1</u>",$a);
$a=preg_replace("/\[cn\](.*?)\[\/cn\]/si","<center>\\1</center>",$a);
$a=preg_replace("/\[bq\](.*?)\[\/bq\]/si","<blockquote>\\1</blockquote>",$a);
$a=preg_replace("/\[img=(.*?)\]/si","<img src=\"\\1\" border=\"0\">",$a);
$a=preg_replace("/\[img\](.*?)\[\/img\]/si","<img src=\"\\1\" border=\"0\">",$a);
$a=preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/si","<a href=\"\\1\" target=\"_blank\">\\2</a>",$a);
$a=preg_replace("/\[quote=(.*?)\](.*?)\[\/quote\]/si","<blockquote><i><b>Originally posted by \\1:</b><br>\\2</i></blockquote>",$a);
return $a;
}



As is evident in the function, the string given to the function ($a) can utilize the following UBB code which will be converted into functional HTML:
[LIST]
[*][hr] (horizontal rule)
[*][b][/b] (bold)
[*][i][/i] (italics)
[*][u][/u] (underlined)
[*][cn][/cn] (centered)
[*][bq][/bq] (blockquote)
[*][img=] (image)
[*][img][/img] (another common image UBB code)
[*][url=][/url] (url and name of link)
[*][quote=][/quote] (quote author and text)
[/LIST]

If you follow the format in the function and know some basic regular expression it's a quick job to edit or add new code tags.

As for use, simply run the string in question though ubbconvert() and echo the output. Remember that this code is specific to converting UBB code and you need to already be pacifying HTML, javascript and event handlers such as OnLoad, OnClick, etc for your application to not have obvious security holes.

penguinmama

12.***.***.***
1,936 days ago
I always wondered how they did that. Nifty!

I have a book about PHP that works one through creating online forums. I may try it sometime.