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.

Introducing Regular Expressions<br />

127<br />

For example, the following matches bob at the start of a string:<br />

^bob<br />

This pattern matches com at the end of a string:<br />

com$<br />

Finally, this pattern matches a string containing only a single character from a to z:<br />

^[a-z]$<br />

Branching<br />

You can represent a choice in a regular expression with a vertical pipe. For example, if<br />

you want to match com, edu, or net, you can use the following expression:<br />

com|edu|net<br />

Matching Literal Special Characters<br />

If you want to match one of the special characters mentioned in the preceding sections,<br />

such as ., {, or $, you must put a backslash (\) in front of it. If you want to represent a<br />

backslash, you must replace it with two backslashes (\\).<br />

Be careful to put your regular expression patterns in single-quoted strings in <strong>PHP</strong>.<br />

Using regular expressions in double-quoted <strong>PHP</strong> strings adds unnecessary complications.<br />

<strong>PHP</strong> also uses the backslash to escape special characters—such as a backslash. If you want<br />

to match a backslash in your pattern, you need to use two to indicate that it is a literal<br />

backslash, not an escape code.<br />

Similarly, if you want a literal backslash in a double-quoted <strong>PHP</strong> string, you need to<br />

use two for the same reason.The somewhat confusing, cumulative result of these rules is<br />

that a <strong>PHP</strong> string that represents a regular expression containing a literal backslash needs<br />

four backslashes. The <strong>PHP</strong> interpreter will parse the four backslashes as two.Then the<br />

regular expression interpreter will parse the two as one.<br />

The dollar sign is also a special character in double-quoted <strong>PHP</strong> strings <strong>and</strong> regular<br />

expressions.To get a literal $ matched in a pattern, you would need “\\\$”. Because this<br />

string is in double quotation marks, <strong>PHP</strong> will parse it as \$, which the regular expression<br />

interpreter can then match against a dollar sign.<br />

Reviewing the Special Characters<br />

A summary of all the special characters is shown in Tables 4.4 <strong>and</strong> 4.5.Table 4.4 shows<br />

the meaning of special characters outside square brackets, <strong>and</strong> Table 4.5 shows their<br />

meaning when used inside square brackets.

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

Saved successfully!

Ooh no, something went wrong!