Regular Expressions Cheat Sheet

What are Regular Expressions?

Get started with regex

“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 –

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:

/A([a-zA-Z]{3}) (d{3})$/

(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

Here is a good regex cheat sheet that gives you all the basics of Regular Expression in one page.

What are Regular Expressions
This cheat sheet is credited to Dave Child.

You can download the cheat sheet directly here: PDF Format

Join the Discussion

We are happy that you have chosen to join the discussion BUT we also have rules. Please keep in mind that all comments are moderated according to our privacy policy. Any links are nofollow. Do NOT use keywords in the name field you MUST leave a real name in order to get your comment approved. Spamming for a link will not be tolerated on this site so do not waste your time. Comments must relate to the post topic. This website is here to help people, not for your advertising purposes. Lets have a personal and meaningful conversation.

Your email address will not be published. Required fields are marked *