Page 609 - Beginning PHP 5.3
P. 609
Chapter 18: String Matching with Regular Expressions
Summary
This chapter introduced you to regular expressions, a powerful and compact way to search for
complex patterns of text within strings. You studied the various components of regular expression
syntax, including:
❑ How to include literal characters in regular expressions
❑ How to use character classes to match types of characters, such as letters or digits
❑ Using quantifiers to match the same character more than once in succession
❑ Controlling the amount of text matched through the use of greedy and non - greedy matching
❑ How to use subpatterns to make regular expressions more powerful
❑ Creating alternative patterns to allow for more flexible matching
❑ Using anchors to match text at specific points in the target string
❑ Modifying matching behavior with pattern modifiers
You also explored PHP ’ s various regular expression functions, including:
❑ preg_match() and preg_match_all() for matching strings against regular expressions
❑ preg_quote() for escaping special characters in expressions
❑ preg_grep() for matching arrays of strings
❑ preg_replace() and preg_replace_callback() for replacing pattern matches
with new text
❑ preg_split() to split strings using a regular expression to match delimiters
Along the way you studied example scripts for finding linked URLs in a Web page, as well as validating
and processing user input.
The next chapter looks at XML — a very useful way to store and exchange data — and shows how you
can read and write XML data from within your PHP scripts. Meanwhile, try the following two exercises
to check your understanding of regular expressions. You can find the solutions to these exercises in
Appendix A.
Exercises
1. Write a regular expression that extracts the domain name portion of a Web URL (excluding
the “ www. ” subdomain if supplied). The protocol portion of the URL should be optional.
For example, the expression should extract the domain name “ example.com ” from any of the
following URLs:
❑ http://www.example.com/
❑ http://www.example.com/hello/there.html
571
9/21/09 6:18:04 PM
c18.indd 571
c18.indd 571 9/21/09 6:18:04 PM