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.

The c in strcspn( ) stands for complement—it tells you how much of the start of the<br />

string is not composed of the characters in the character set. Use it when the number of<br />

interesting characters is greater than the number of uninteresting characters. For example,<br />

this function tests whether a string has any NUL-bytes, tabs, or carriage returns:<br />

function has_bad_chars ($str) {<br />

return strcspn($str, "\n\t\0");<br />

}<br />

Decomposing URLs<br />

The parse_url( ) function returns an array of components of a URL:<br />

$array = parse_url(url);<br />

For example:<br />

$bits = parse_url('http://me:secret@example.com/cgi-bin/board?user=fred);<br />

print_r($bits);<br />

Array<br />

(<br />

[scheme] => http<br />

[host] => example.com<br />

[user] => me<br />

[pass] => secret<br />

[path] => /cgi-bin/board<br />

[query] => user=fred<br />

)<br />

The possible keys of the hash are scheme, host, port, user, pass, path, query, and<br />

fragment.<br />

Regular Expressions<br />

If you need more complex searching functionality than the previous methods provide,<br />

you can use regular expressions. A regular expression is a string that represents<br />

a pattern. The regular expression functions compare that pattern to another string<br />

and see if any of the string matches the pattern. Some functions tell you whether<br />

there was a match, while others make changes to the string.<br />

<strong>PHP</strong> provides support for two different types of regular expressions: POSIX and Perlcompatible.<br />

POSIX regular expressions are less powerful, and sometimes slower,<br />

than the Perl-compatible functions, but can be easier to read. There are three uses for<br />

regular expressions: matching, which can also be used to extract information from a<br />

string; substituting new text for matching text; and splitting a string into an array of<br />

smaller chunks. <strong>PHP</strong> has functions for all three behaviors for both Perl and POSIX<br />

regular expressions. For instance, ereg( ) does a POSIX match, while preg_match( )<br />

does a Perl match. Fortunately, there are a number of similarities between basic<br />

POSIX and Perl regular expressions, so we’ll cover those before delving into the<br />

details of each library.<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Regular Expressions | 95

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

Saved successfully!

Ooh no, something went wrong!