Regular Expressions
If you need more complex searching functionality than the previous methods provide, you can use regular expressions. A regular expression is a string that represents a pattern. The regular expression functions compare that pattern to another string and see if any of the string matches the pattern. Some functions tell you whether there was a match, while others make changes to the string.
PHP provides support for two different types of regular expressions:
POSIX and Perl-compatible. POSIX regular expressions are less
powerful, and sometimes slower, than the Perl-compatible functions,
but can be easier to read. There are three uses for regular
expressions: matching, which can also be used to
extract information from a string; substituting new text
for matching text; and
splitting a string into an
array of smaller chunks. PHP has functions for all three behaviors
for both Perl and POSIX regular expressions. For instance, ereg( )
does a POSIX match, while preg_match( ) does a Perl match.
Fortunately, there are a number of similarities between basic POSIX
and Perl regular expressions, so we’ll cover those
before delving into the details of each library.
The Basics
Most characters in a regular expression are literal characters,
meaning that they match only themselves. For instance, if you search
for the regular expression "cow" in the string "Dave was a cowhand",
you get a match because "cow" occurs in that string.
Some characters, though, have special meanings ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access