25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

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

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

92 ” Strings And Patterns<br />

Sub-Expressions<br />

A sub-expression is a regular expression contained within the main regular expression<br />

(or another sub-expression); you define one by encapsulating it in parentheses:<br />

/a(bc.)e/<br />

This expression will match the letter a, followed by the letters b and c, followed by<br />

any character and, finally the letter e. As you can see, sub-expressions by themselves<br />

do not have any influence on the way a regular expression is executed; however, you<br />

can use them in conjunction with quantifiers to allow for complex expressions to<br />

happen more than once. For example:<br />

/a(bc.)+e/<br />

This expression will match the letter a, followed by the expression bc. repeated one<br />

or more times, followed by the letter e.<br />

Sub-expressions can also be used as capturing patterns, which we will examine in<br />

the next section.<br />

Matching and Extracting Strings<br />

The preg_match() function can be used to match a regular expression against a given<br />

string. The function returns integer 1 if the match is successful, and can return all<br />

the captured subpatterns in an array if an optional third parameter is passed by reference.<br />

Here’s an example:<br />

$name = "Davey Shafik";<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

// Simple match<br />

$regex = "/[a-zA-Z\s]/";<br />

if (preg_match($regex, $name)) {<br />

// Valid Name<br />

}<br />

// Match with subpatterns and capture

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

Saved successfully!

Ooh no, something went wrong!