Friday, November 1, 2013

OpenBD, parsing BBCode, loops and a simple Regex solution

Lately I've been working on a bunch of AJAX applications, more or less chat-oriented, and they both needed variations of BBCode, so I started working on it.

My first iteration used a loop looking for the bbcode, counting the number of times and if it came up uneven with the ending bbcode it would add the closing code at the end of the text, all in all it was a very clunky way of doing things but it worked well.

The latest project however, I decided that there had to be a better way of doing it, so I started thinking about using regex, I came up with my own variant but it didn't work when you nest different bbcodes (I'm not very good with regex) but with some paid help on Fiverr I got the following regex and it works very nicely:


It's pretty simple, but works nicely, I haven't seen any other solution this straight forward out there so I figured I'd share this one.
The next problem was the url bbcode, now in this application we're only using [url][/url] because the link name will be same as the actual link, no way to hide a different link under a false name.
This is what we came up with:


The basic idea is that it works with or without the user writing out http:// and it supports variations such as https://, the original regex I came up with broke if the user only wrote www.link.com and the finished link was handled wrongly, making the browser look for a local page instead of the proper url.

So there you have it, nice and simple, feel free to use it.