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.

This code snippet takes several seconds to report failure:<br />

$p = '/(a+|b+)*\.+$/';<br />

$s = 'abababababbabbbabbaaaaaabbbbabbababababababbba..!';<br />

if (preg_match($p, $s)) {<br />

echo "Y";<br />

} else {<br />

echo "N";<br />

}<br />

This is because the regular expression engine tries all the different places to start the<br />

match, but has to backtrack out of each one, which takes time. If you know that<br />

once something is matched it should never be backed out of, you should mark it<br />

with (?>subpattern):<br />

$p = '/(?>a+|b+)*\.+$/';<br />

The cut never changes the outcome of the match; it simply makes it fail faster.<br />

Conditional Expressions<br />

A conditional expression is like an if statement in a regular expression. The general<br />

form is:<br />

(?(condition)yespattern)<br />

(?(condition)yespattern|nopattern)<br />

If the assertion succeeds, the regular expression engine matches the yespattern. With<br />

the second form, if the assertion doesn’t succeed, the regular expression engine skips<br />

the yespattern and tries to match the nopattern.<br />

The assertion can be one of two types: either a backreference, or a lookahead or<br />

lookbehind match. To reference a previously matched substring, the assertion is a<br />

number from 1–99 (the most backreferences available). The condition uses the pattern<br />

in the assertion only if the backreference was matched. If the assertion is not a<br />

backreference, it must be a positive or negative lookahead or lookbehind assertion.<br />

Functions<br />

There are five classes of functions that work with Perl-compatible regular expressions:<br />

matching, replacing, splitting, filtering, and a utility function for quoting text.<br />

Matching<br />

The preg_match( ) function performs Perl-style pattern matching on a string. It’s the<br />

equivalent of the m// operator in Perl. The preg_match( ) function takes the same<br />

arguments and gives the same return value as the ereg( ) function, except that it<br />

takes a Perl-style pattern instead of a standard pattern:<br />

$found = preg_match(pattern, string [, captured ]);<br />

110 | Chapter 4: Strings<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!