Specifications

(This rule applies universally to special characters, so if you have \\ in your string, you need
to replace it with \\\\.)
PHP provides two functions specifically designed for escaping characters. Before you write
any strings into a database, you should reformat them with AddSlashes(), for example:
$feedback = AddSlashes($feedback);
Like many of the other string functions, AddSlashes() takes a string as parameter and returns
the reformatted string.
When you use AddSlashes(), the string will be stored in the database with the slashes in it.
When you retrieve the string, you will need to remember to take the slashes out. You can do
this using the StripSlashes() function:
$feedback = StripSlashes($feedback);
Figure 4.3 shows the actual effects of using these functions on the string.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
101
FIGURE 4.3
After calling the AddSlashes() function, all the quotes have been slashed out. StripSlashes() removes the slashes.
You can also set PHP up to add and strip slashes automatically. This is called using magic
quotes. You can read more about magic quotes in Chapter 21, Other Useful Features.
Joining and Splitting Strings with String Functions
Often, we want to look at parts of a string individually. For example, we might want to look at
words in a sentence (say for spellchecking), or split a domain name or email address into its
06 7842 CH04 3/6/01 3:41 PM Page 101