UltraMega Blog
7Apr/099

Creating a BBCode Parser

Have you ever wanted to implement BBCode, the special formatting codes used by forums, into your own PHP scripts? Well, it's actually pretty easy to accomplish using some simple regular expressions and the preg_replace PHP function. This mini-tutorial will show you how to create a function that you can use on any string to convert BBCode into its XHTML equivalent.

The advantage to using BBCode instead of allowing XHTML in user input is that it allows users to safely format their content without the risk of invalid code breaking the page formatting. It also tends to be easier to understand BBCode over XHTML due to its simplified syntax.

31Mar/091

Easy Text Validation Without Regular Expressions

Filtering data from user input and other external sources is the most important part of writing secure code, but it's also handy to make sure users supply the correct type of info to a registration form for example. Sometimes it's simply making sure something is a number or of a certain length, but other times it's something that follows a specific pattern (like an email address). This used to be a job for complex regular expressions, but fortunately, there is an easier and more reliable solution.

PHP 5.2.0 and up comes with a very convenient set of data filtering functions. These functions allow you to easily validate common things such as emails and URLs, that would otherwise require complex regular expressions that don't always work. This tutorial will focus on the simplest function filter_var().