Page 580 - Beginning PHP 5.3
P. 580
Part III: Using PHP in Practice
Finally, to start the search from a particular position in the target string, pass the position as the fifth
argument:
echo preg_match( “/world/”, “Hello, world!”, $match, 0, 8 ); // Displays “0”
(This example displays zero because the “ world ” text starts at position 7 in the target string.)
Now that you know how PHP ’ s regular expression matching function works, it ’ s time to learn how to
write regular expressions.
Exploring Regular Expression Syntax
Although a complex regular expression can look like Greek to the newcomer, regular expressions are
nothing more than a set of simple rules encoded in a string. Once you understand how the various rules
work you ’ ll be able to read any regular expression with relative ease.
In the following sections you learn some useful regular expression rules. Though this list of rules isn ’ t
100 percent complete, it ’ s more than adequate for most string matching scenarios. (For a seriously in -
depth treatment of regular expressions, try the book Mastering Regular Expressions by Jeffrey E. F. Friedl,
published by O ’ Reilly, ISBN 1 - 56592 - 257 - 3.)
Matching Literal Characters
The simplest form of regular expression pattern is a literal string. In this situation, the string stored in the
pattern matches the same string of characters in the target string, with no additional rules applied.
As you ’ ve already seen, alphabetical words such as “ hello ” are treated as literal strings in regular
expressions. The string “ hello ” in a regular expression matches the text “ hello ” in the target string.
Similarly, many other characters — such as digits, spaces, single and double quotes, and the % , & , @ , and
# symbols — are treated literally by the regular expression engine.
However, as you see later, some characters have special meanings within regular expressions. These
nineteen special characters are:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | :
If you want to include any character from this list literally within your expression, you need to escape it
by placing a backslash ( \ ) in front of it, like so:
echo preg_match( “/love\?/”, “What time is love?” ); // Displays “1”
Because the backslash is itself a special character, you need to escape it with another backslash ( \\ ) if
you want to include it literally in an expression. What ’ s more, because a backslash followed by another
character within a string is itself seen as an escaped character in PHP, you usually need to add a third
backslash ( \\\ ). Phew!
In addition, if you use your delimiter character within your expression, you need to escape it:
542
9/21/09 6:17:51 PM
c18.indd 542
c18.indd 542 9/21/09 6:17:51 PM