Specifications

The length value is optional and represents the point at which PHP will stop replacing. If you
dont supply this value, the string will be replaced from start to the end of the string.
If length is zero, the replacement string will actually be inserted into the string without over-
writing the existing string.
A positive length represents the number of characters that you want replaced with the new
string.
A negative length represents the point at which youd like to stop replacing characters,
counted from the end of the string.
Introduction to Regular Expressions
PHP supports two styles of regular expression syntax: POSIX and Perl. The POSIX style of
regular expression is compiled into PHP by default, but you can use the Perl style by compil-
ing in the PCRE (Perl-compatible regular expression) library. Well cover the simpler POSIX
style, but if youre already a Perl programmer, or want to learn more about PCRE, read the
online manual at
http://php.net.
So far, all the pattern matching weve done has used the string functions. We have been limited
to exact match, or to exact substring match. If you want to do more complex pattern matching,
you should use regular expressions. Regular expressions are difficult to grasp at first but can be
extremely useful.
The Basics
A regular expression is a way of describing a pattern in a piece of text. The exact (or literal)
matches weve done so far are a form of regular expression. For example, earlier we were
searching for regular expression terms like “shop” and “delivery”.
Matching regular expressions in PHP is more like a strstr() match than an equal comparison
because you are matching a string somewhere within another string. (It can be anywhere
within that string unless you specify otherwise.) For example, the string “shop” matches the
regular expression “shop”. It also matches the regular expressions “h”, “ho”, and so on.
We can use special characters to indicate a meta-meaning in addition to matching characters
exactly.
For example, with special characters you can indicate that a pattern must occur at the start or
end of a string, that part of a pattern can be repeated, or that characters in a pattern must be of
a particular type. You can also match on literal occurrences of special characters. Well look at
each of these.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
109
06 7842 CH04 3/6/01 3:41 PM Page 109