EMAIL ME WHEN AVAILABLE We will inform you when the product arrives in stock. Just leave your valid email address below.
Email Quantity We won't share your address with anybody else.

PHP – Regular Expression Survival Guide

Regular expressions are torture! Some people are masacists and enjoy them but for the rest of us they are a necessary evil we dread writing but have great respect for their power. Regular Expressions are commonly used for form validation, data parsing, url rewrites and replacing values in a string. Regular Expressions can be used used with just about any language, they work especially great with Javascript’s replace() and PHP’s preg_replace(). They are also extremely useful for apache mod rewrite and IIS url rewrite Here are some survival tips for Regular Expressions

1) Hire someone else to do it!

Hire someone to write your regular expression for $5 using I highly recomend ohpointybird. He whipped out a complicated regular expression for me in less than an hour at 11pm on a week night.

2) Online Video Tutorials

So you actually want to learn how to do it yourself? Here are the best free video tutorials to help you become an expert.

3) Online Regular Expression Online Builder

Allows you to create and test regualr expression as well as a community-driven library of regular expressions.

4) Regular Expression Library

A library with over 3000 regular expressions. Why reinvent the wheel if someone else has already created it for you?

5) Regular Expression Video Training

6) Regular Expression Builder

Expresso editor is a full-featured wizard for creating regular expressions.

7) Regular Expression Cheat Sheet

The Regular Expressions cheat sheet is a one-page reference sheet. It is a guide to patterns in regular expressions, and is not specific to any single language.

My most commonly used regular expressions:

1) Validate domain name

Verify if a string is a valid domain name.
$url = "";  if (preg_match(''/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i'', $url)) {      echo "Your url is ok.";  } else {      echo "Wrong url.";  }

2) Highlight a word from a text

This very useful regular expression find a specific word in a text, and highlight it. Extremely useful for search results.
$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";  $text = preg_replace("/b(regex)b/i", ''<span style="background:#5fc9f6">1</span>'', $text);  echo $text;

3) Validate an URL

Is a particular url valid? The following regexp will let you know.
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/

4) Validate US phone number

This regexp will verify that a US phone number is valid.

5) Test if a password is strong

Weak passwords are one of the quickest ways to get hacked. The following regexp will make sure that:
  • Passwords will contain at least (1) upper case letter
  • Passwords will contain at least (1) lower case letter
  • Passwords will contain at least (1) number or special character
  • Passwords will contain at least (8) characters in length
  • Password maximum length should not be arbitrarily limited

6) Text Snippet, No Cut-Off In Middle of Word

Easily one of my favorite functions. This regular expression accepts a string and a character limit, and returns a shortened string without cutting off the middle of a word:
function textSnippet($str, $num) {
$string_match = preg_match("/^([\s\S]){1," . $num . "}([\s\.])/", $str, $matches);
$shortened_string = $matches[0];
return $shortened_string . ''...'';
Sample string: A super long string that goes on and on forever Returns: A super long string…

7) Extract or Parse Questions from a String

If you have a discussion forum or support center sometimes it”s helpful to extract the actual question for meta data about the submission.
preg_match_all("/([^\s\.\?\n\r!][^\.\?\n\r!]*\?|(Who|What|When|Why|Where|How)\s[^\.\?\n\r!]*[\.\?])/", $string, $out);



Pin It

Trackback from your site.


This information box about the author only appears if the author has biographical information. Otherwise there is not author box shown. Follow YOOtheme on Twitter or read the blog.

Leave a comment