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:
It does this by searching for:
Sequential alphanumeric and punctuation characters, which form the username
The at symbol (
A group of alphanumeric and punctuation characters, which forms the first part of the domain name
A period, which separates the domain name from the extension
A two- to four-character alpha string, which signifies the top level domain—for example,
The descriptors used in the regular expression are:
A boundary point of a word
One of anything inside the brackets:
a, A, b, B
A total of between 2 and 4 of anything preceding the brackets