O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Pattern Matching

Pattern matching allows you to build expressions that match strings using a specific matching syntax called a regular expression. Regular expressions allow you to perform searching tasks such as separating out a certain tag for an incoming text file, or validating user input such as email addresses.

The easiest way to use regular expressions in PHP is to use the PCRE (Perl-compatible regular expressions) extension. This extension is installed by default, so it should be part of your PHP environment. PHP also supports a style of regular expression matching functions called ereg that are older and less compatible than PCRE functions.

A regular expression is really just a string. The string uses a combination of special characters and literals to allow matching of other strings. For example, the following string describes an email address:

\b[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}\b

It does this by searching for:

  1. Sequential alphanumeric and punctuation characters, which form the username

  2. The at symbol (@)

  3. A group of alphanumeric and punctuation characters, which forms the first part of the domain name

  4. A period, which separates the domain name from the extension

  5. A two- to four-character alpha string, which signifies the top level domain—for example, com and net

The descriptors used in the regular expression are:

\b

A boundary point of a word

[aAbB]

One of anything inside the brackets: a, A, b, B

{2,4}

A total of between 2 and 4 of anything preceding the brackets

A-Z

Any ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required