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.

314<br />

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

The only difference between str_replace() <strong>and</strong> preg_replace() on a basic level is that the element<br />

passed to preg_replace() for the pattern must use delimiters, which let the function know which part of<br />

the regex is the pattern <strong>and</strong> which part consists of modifiers, or flags that affect how the pattern matches.<br />

You’ll learn more about modifiers a little later in this section.<br />

The delimiters for regex patterns in preg_replace() can be any non-alphanumeric, non-backslash,<br />

<strong>and</strong> non-whitespace characters placed at the beginning <strong>and</strong> end of the pattern. Most commonly,<br />

forward slashes (/) or hash signs (#) are used. For instance, if you want to search for the letters cat in a<br />

string, the pattern would be /cat/ (or #cat#, %cat%, @cat@, <strong>and</strong> so on).<br />

Choosing Regexes vs. Regular String Replacement<br />

To explore the differences between str_replace() <strong>and</strong> preg_replace(), try using both functions to wrap<br />

any occurrence of the word regular with tags. Make the following modifications to regex.php:<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!