Learning Regular Expressions in PHP

I'll admit it, I'm a regex nerd. I love those little blighters and they've saved me on countless occasions.

For those who don't know, a Regular Expression, or regex for short, is a way of finding patterns within strings. If you've ever seen a url or email address be magically turned from text into a hyperlink then you'll have seen one in action.

Regular_expressions
http://xkcd.com/208/ Comic from XKCD showing how regex skills can be used in everyday life.

So, you want to learn regular expressions?

PHP uses both eregi and Perl Compatible (PCRE) regular expressions. As of PHP 5.3, the eregi library is deprecated, so always make sure you're learning the PCRE style of regex.

Here are some awesomely great resources to help you learn regex's in PHP;

PHP Manual
Kind of a no-brainer, but the manual has all you need to know about talking regex's in PHP.

Regular-Expressions.info
I once spent a very nerdy and lonely weekend working methodically through this website. It is brilliant. The syntax, the modifiers, everything is covered here. Use it.

Reggy
If you're lucky enough to be on OS X, then Reggy is an absolute godsent. Simply type your Regex in the top box, and the text your running it against, and Reggy will show you exactly what is being matched.

The Regex Coach
If you're on Windows, I've heard good things about this little bit of freeware that lets you test out your regexs. 

My own tips
My tips for working with regexs are the following;

  • Start small, build simple ones and work up.
  • If possible, always use someone else's rather than your own, they've probably done more research than you. This is especially true of emails and urls.
  • If all else fails, escape stuff using \ 

Hope that helps someone!