02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

318<br />

CHAPTER 9 ■ PERFORMING FORM VALIDATION WITH REGULAR EXPRESSIONS<br />

Getting Fancy with Backreferences<br />

The power of regexes starts to appear when you apply one of their most useful features: grouping <strong>and</strong><br />

backreferences. A group is any part of a pattern that is enclosed in parentheses. A group can be used in<br />

the replacement string (or later in the pattern) with a backreference, a numbered reference to a named<br />

group.<br />

This all sounds confusing, but in practice it’s quite simple. Each set of parentheses from left to right<br />

in a regex is stored with a numeric backreference, which can be accessed using a backslash <strong>and</strong> the<br />

number of the backreference (\1) or <strong>by</strong> using a dollar sign <strong>and</strong> the number of the backreference ($1).<br />

The benefit of this is that it gives regexes the ability to use the matched value in the replacement,<br />

instead of a predetermined value as in str_replace() <strong>and</strong> its ilk.<br />

To keep the replacement contents in your previous example in the proper case, you need to use two<br />

occurrences of str_replace(); however, you can achieve the same effect <strong>by</strong> using a backreference in<br />

preg_replace()with just one function call.<br />

Make the following modifications to regex.php to see the power of backreferences in regexes:<br />

<br />

<br />

<br />

<br />

Regular Expression Demo<br />

<br />

em {<br />

background-color: #FF0;<br />

border-top: 1px solid #000;<br />

border-bottom: 1px solid #000;<br />

}<br />

<br />

<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!