#native_company# #native_desc#
#native_cta#

PHP and Regular Expressions 101

By Mitchell Harper
on May 31, 2007

Introduction
Regular expressions are one of those quirky features that popup in a variety of programming languages,
but because they seem to be a difficult concept to grasp, many developers push them away into the corner,
forgetting that they even exist.
A regular expression is a specially formatted pattern that can be used to find instances of one
string in another. Several programming languages including Visual Basic, Perl, JavaScript and PHP
support regular expressions, and hopefully by the end of this primer you should be able to implement
some basic regular expression functionality into your PHP pages.
Let’s start by taking a look at what a regular expression is, and why you’d want to use them in
your PHP pages.
What is a regular expression?
What do you think it is that separates programs like BBEdit and notepad from the good old
console-based text editors? Both support text input and let you save that text into a file, however
modern text editors also support other functionality including find-replace tools, which makes editing
a text file that much easier.
Regular expressions are similar, only better. Think of a regular expression as an extremely
advanced find-replace tool that saves us the pain of having to write custom data validation routines
to check e-mail addresses, make sure phone numbers are in the correct format, etc.
One of the most common functions of any program is data validation, and PHP comes bundled with
several text validation functions that allow us to match a string using regular expressions, making
sure there’s a space here, a question mark there, etc.
What you may not know however, is that regular expressions are simple to implement, and once
you’ve mastered a few regular expressions (which are specially formatted strings that we can use
to tell the regular expression engine the portion of a string we want to match) you’ll be asking
yourself why you left regular expressions in the corner for so long.

Note: PHP has two sets of functions for dealing with the two types of
regular expression patterns: Perl 5 compatible patterns, and Posix standard compatible patterns. In
this article we will be looking at the ereg function and working with search expressions
that conform to the Posix standard. Although they don’t offer as much power as Perl 5 patterns, they’re
a great way to start learning regular expressions. If you’re interested in PHP’s support for Perl 5
compatible regular expressions, then see the PHP.net site for details on
the preg set of PHP functions.