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

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

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

*<br />

* Start <strong>by</strong> simply outputting the data<br />

*/<br />

echo $string;<br />

?><br />

<br />

<br />

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

Save this file, then load http://localhost/regex.php in your browser to view the sample script (see<br />

Figure 9-1).<br />

Figure 9-1. The sample file for testing regular expressions<br />

Replacing Text with Regexes<br />

To test regular expressions, you’ll wrap matched patterns with tags, which are styled in the test<br />

document to have top <strong>and</strong> bottom borders, as well as a yellow background.<br />

Accomplishing this with regexes is similar using str_replace() in <strong>PHP</strong> with the preg_replace()<br />

function. A pattern to match is passed, followed <strong>by</strong> a string (or pattern) to replace the matched pattern<br />

with. Finally, the string within which the search is to be performed is passed:<br />

preg_replace($pattern, $replacement, $string);<br />

■ Note The p in preg_replace() signifies the use of PCRE. <strong>PHP</strong> also has ereg_replace(), which uses the<br />

slightly different POSIX regular expression syntax; however, the ereg family of functions has been deprecated as<br />

of <strong>PHP</strong> 5.3.0.<br />

313

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

Saved successfully!

Ooh no, something went wrong!