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.
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. For instance, preg_match() does a regular expression
match.
Perl has long been considered the benchmark for powerful regular
expressions. PHP uses a C library called pcre to
provide almost complete support for Perl’s arsenal of regular expression
features. Perl regular expressions act on arbitrary binary data, so you
can safely match with patterns or strings that contain the NUL-byte
(\x00).
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 have special meanings in regular expressions.
For instance, a caret (^) at the beginning of a regular expression indicates that it must match the beginning of the string (or, more ...
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