13.09.2016 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

$toaddress = “retail@example.com”;<br />

} else if (eregi(“deliver|fulfill”, $feedback)) {<br />

$toaddress = “fulfillment@example.com”;<br />

} else if (eregi(“bill|account”, $feedback)) {<br />

$toaddress = “accounts@example.com”;<br />

}<br />

if (eregi(“bigcustomer\.com”, $email)) {<br />

$toaddress = “bob@example.com”;<br />

}<br />

Replacing Substrings with Regular Expressions<br />

You can also use regular expressions to find <strong>and</strong> replace substrings in the same way as<br />

you used str_replace().The two functions available for this task are ereg_replace()<br />

<strong>and</strong> eregi_replace().The function ereg_replace() has the following prototype:<br />

string ereg_replace(string pattern, string replacement, string search);<br />

This function searches for the regular expression pattern in the search string <strong>and</strong><br />

replaces it with the string replacement.<br />

The function eregi_replace() is identical but, again, is not case sensitive.<br />

Splitting Strings with Regular Expressions<br />

Another useful regular expression function is split(), which has the following prototype:<br />

array split(string pattern, string search[, int max]);<br />

This function splits the string search into substrings on the regular expression pattern<br />

<strong>and</strong> returns the substrings in an array.The max integer limits the number of items that<br />

can go into the array.<br />

This function can be useful for splitting up email addresses, domain names, or dates.<br />

For example,<br />

$address = “username@example.com”;<br />

$arr = split (“\.|@”, $address);<br />

while (list($key, $value) = each ($arr)) {<br />

echo “”.$value;<br />

}<br />

This example splits the hostname into its five components <strong>and</strong> prints each on a separate<br />

line.<br />

username<br />

@<br />

example<br />

.<br />

com

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

Saved successfully!

Ooh no, something went wrong!