“In computing, a regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters” – As quoted from Wikipedia – http://en.wikipedia.org/wiki/Regular_expression
Regular Expressions are often thought of as extremely complicated things. This is only partly true.
While you may already be familiar (and even using) strpos() and/or str_replace() in your scripts, these functions are fairly limiting; you can generally only search/replace for single characters or words. Alternatively preg_match() and/or preg_replace() open up a whole new world of pattern matching.
Let’s say we want to match a web hosting promo code consisting of three letters followed by three numbers. This would be extremely tough using strpos() as we’d have to think of every combination possible – we’d need around 17.5million lines of code! With regular expressions and the preg_match() function, we could do it simply using:
(for demonstration purposes, I’ve grouped each pattern ‘type’ inside brackets).
Regular expressions have a couple of shorthand character classes that allow you match the most common characters without less typing: d matches a digit (0-9) w matches a word character (a-z, 0-9 plus _) s matches whitespace characters (space, line breaks and tabs) Each group in our regex is restricted to three characters in length using the curly braces. You’ll notice I’m specifying a letter range above, as ‘Xw* would also match numbers and in this case, I only want the letters a to z (in either lower- or upper-case).
One caveat is that regular expressions can be overkill. If you need to match/replace a single known word, using strpos() and/or str_replace() will be the quicker solution.
There are many more possible regex solutions and there are even books devoted to the subject! To get started, I’d recommend the ‘PHP Regex’ tutorial by Kevin Watson at www.phpro.org/tutorials/Introduction-to-PHP-Regex.html.
Here is a good regex cheat sheet that gives you all the basics of Regular Expression in one page.
You can download the cheat sheet directly here: PDF Format