05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Alternatives<br />

You can use the vertical pipe (|) character to specify alternatives in a regular<br />

expression:<br />

ereg('cat|dog', 'the cat rubbed my legs'); // returns true<br />

ereg('cat|dog', 'the dog rubbed my legs'); // returns true<br />

ereg('cat|dog', 'the rabbit rubbed my legs'); // returns false<br />

The precedence of alternation can be a surprise: '^cat|dog$' selects from '^cat' and<br />

'dog$', meaning that it matches a line that either starts with "cat" or ends with<br />

"dog". If you want a line that contains just "cat" or "dog", you need to use the regular<br />

expression '^(cat|dog)$'.<br />

You can combine character classes and alternation to, for example, check for strings<br />

that don’t start with a capital letter:<br />

ereg('^([a-z]|[0-9])', 'The quick brown fox'); // returns false<br />

ereg('^([a-z]|[0-9])', 'jumped over'); // returns true<br />

ereg('^([a-z]|[0-9])', '10 lazy dogs'); // returns true<br />

Repeating Sequences<br />

To specify a repeating pattern, you use something called a quantifier. The quantifier<br />

goes after the pattern that’s repeated and says how many times to repeat that pattern.<br />

Table 4-6 shows the quantifiers that are supported by both POSIX and Perl regular<br />

expressions.<br />

Table 4-6. Regular expression quantifiers<br />

Quantifier Meaning<br />

? 0 or 1<br />

* 0 or more<br />

+ 1 or more<br />

{n} Exactly n times<br />

{n,m} At least n, no more than m times<br />

{n,} At least n times<br />

To repeat a single character, simply put the quantifier after the character:<br />

ereg('ca+t', 'caaaaaaat'); // returns true<br />

ereg('ca+t', 'ct'); // returns false<br />

ereg('ca?t', 'caaaaaaat'); // returns false<br />

ereg('ca*t', 'ct'); // returns true<br />

With quantifiers and character classes, we can actually do something useful, like<br />

matching valid U.S. telephone numbers:<br />

ereg('[0-9]{3}-[0-9]{3}-[0-9]{4}', '303-555-1212'); // returns true<br />

ereg('[0-9]{3}-[0-9]{3}-[0-9]{4}', '64-9-555-1234'); // returns false<br />

98 | Chapter 4: Strings<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!