Page 602 - Beginning PHP 5.3
P. 602
Part III: Using PHP in Practice
This code displays:
Array
(
[0] = >
[1] = > hello
[2] = >
[3] = >
[4] = >
[5] = > goodbye
[6] = >
)
This is because the regular expression causes any of the apostrophe, comma, and space characters to be
treated as delimiters. So the string is split right at the start and end because the first and last characters
are delimiters, and is also split three times between “ hello ” and “ goodbye ” because preg_split()
“ sees ” three empty strings between the apostrophe, comma, and space characters in the input string.
Naturally these empty substrings are unwanted. By setting the PREG_SPLIT_NO_EMPTY flag you can
easily remove these substrings from the resulting array:
$text = “’hello’, ‘goodbye’”;
$letters = preg_split( “/[‘, ]/”, $text, -1, PREG_SPLIT_NO_EMPTY );
echo “ < pre > ”;
print_r( $letters );
echo “ < /pre > ”;
This code produces the desired result:
Array
(
[0] = > hello
[1] = > goodbye
)
Try It Out Validate Form Input
Regular expressions are often used to check that user input is of the correct format. For example, you
can use a regular expression to determine if a user-supplied date field contains a correctly formatted
date string, or if a supplied email address follows the standard rules for email addresses.
This example script creates an order form for an imaginary company selling three product ranges:
SuperWidgets (with product codes of “SWnn”, where “nn” is a two-digit number), MegaWidgets
(with products codes of “MWnn”), and WonderWidgets (with product codes of “WWnn”). The user
can enter his email address, phone number, and the product codes to order. The script then validates
both the email address and phone number fields, and also converts any supplied, valid product codes
to a more human-readable form to display to the user in the confirmation page.
Save the following script as order_form.php in your document root folder.
564
9/21/09 6:18:01 PM
c18.indd 564 9/21/09 6:18:01 PM
c18.indd 564