13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

116 Chapter 4 String Manipulation <strong>and</strong> Regular Expressions<br />

If you see this result, it means that your configuration of <strong>PHP</strong> is set up to add <strong>and</strong> strip<br />

slashes automatically.This capability is controlled by the magic_quotes_gpc configuration<br />

directive in its name.The letters gpc, which is turned on by default in new installations<br />

of <strong>PHP</strong>, st<strong>and</strong> for GET, POST, <strong>and</strong> cookie.This means that variables coming from<br />

these sources are automatically quoted.You can check whether this directive is switched<br />

on in your system by using the get_magic_quotes_gpc() function, which returns true<br />

if strings from these sources are being automatically quoted for you. If this directive is on<br />

in your system, you need to call stripslashes() before displaying user data; otherwise,<br />

the slashes will be displayed.<br />

Using magic quotes allows you to write more portable code.You can read more<br />

about this feature in Chapter 24, “Other Useful Features.”<br />

Joining <strong>and</strong> Splitting Strings with String<br />

Functions<br />

Often, you may want to look at parts of a string individually. For example, you might<br />

want to look at words in a sentence (say, for spellchecking) or split a domain name or<br />

email address into its component parts. <strong>PHP</strong> provides several string functions (<strong>and</strong> one<br />

regular expression function) that allow you to do this.<br />

In the example, Bob wants any customer feedback from bigcustomer.com to go<br />

directly to him, so you can split the email address the customer typed into parts to find<br />

out whether he or she works for Bob’s big customer.<br />

Using explode(), implode(), <strong>and</strong> join()<br />

The first function you could use for this purpose, explode(), has the following prototype:<br />

array explode(string separator, string input [, int limit]);<br />

This function takes a string input <strong>and</strong> splits it into pieces on a specified separator<br />

string.The pieces are returned in an array.You can limit the number of pieces with the<br />

optional limit parameter.<br />

To get the domain name from the customer’s email address in the script, you can use<br />

the following code:<br />

$email_array = explode(‘@’, $email);<br />

This call to explode() splits the customer’s email address into two parts: the username,<br />

which is stored in $email_array[0], <strong>and</strong> the domain name, which is stored in

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!