Love them or hate them, regular expressions are here to stay. When it comes to quickly dealing with large blocks of data, batch processing operations or screen scraping, regular expressions are often the most effective solution. There’s just one problem, though – learning them can be as hard as learning a new language altogether. Here’s how to get off to a flying start.
First, you need to how regular expressions work. Stick with PCRE – the preg_* functions – they’re faster, more reliable and expressions for them are more common. The different styles of regular expressions each define a mini language for matching patterns within a block of text. Screen scraping is probably the most popular example. Consider this:
What if you wanted to programmatically extract the link URLs and text from each of these? At this level of simplicty, some basic explode()s might be enough, and when you need to be more tolerant for the data, XML parsing is probably the way to go. But for now, just looking at that, regular expressions would be the easiest way. And we can build a pattern that defines what is to be matched so that the regular expression engine (in this case, PCRE) will find all matches and give them to us.
One of the best ways to understand regular expressions in practise, I find, is to consider mod_rewrite. You’ve seen those fantastic URLs on websites – e.g. http://example.com/users/myusername – these don’t actually exist as a file, but we can use Apache’s mod_rewrite engine to “rewrite” these URLs to other URLs. We might make that /users/(some username) go to /users.php?username=(the username). The best tutorial for this, by far, is the corz.org htaccess tips and tricks guide. Have a very thorough read through this and experiment with it extensively before you go on.
Next, get equipped to test out regular expressions. You’re probably using Firefox. If you aren’t, get it. Then get the Regular Expressions Tester Firefox extension. This will be invaluable for experimenting with regular expressions – the best way to learn.
Of course, you’ll need to be familiar with the PHP functions that will provide your regular expression workhorse. Bookmark the preg_match function’s manual entry and refer back to it as you need to. The manual page has some invaluable examples which you should read through extensively.
With all these ready, you’ll be off to a great start. Remember, the best way to learn is to practise — read through real, working code, then write your own. Once you’ve finished all this, you’ll be a regular expression whiz in no time.