This is related somewhat, you do not have to use Geshi, but I wrote a bit of code here Advice for implementing simple regex (for bbcode/geshi parsing) that would help you with the problem.
It can be tweaked to not use GeSHi, just would take a bit of tinkering. Hope it helps ya.