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.

Inline Options<br />

In addition to specifying patternwide options after the closing pattern delimiter, you<br />

can specify options within a pattern to have them apply only to part of the pattern.<br />

The syntax for this is:<br />

(?flags:subpattern)<br />

For example, only the word “<strong>PHP</strong>” is case-insensitive in this example:<br />

preg_match('/I like (?i:<strong>PHP</strong>)/', 'I like pHp'); // returns true<br />

The i, m, s, U, x, and X options can be applied internally in this fashion. You can use<br />

multiple options at once:<br />

preg_match('/eat (?ix:fo o d)/', 'eat FoOD'); // returns true<br />

Prefix an option with a hyphen (-) to turn it off:<br />

preg_match('/(?-i:I like) <strong>PHP</strong>/i', 'I like pHp'); // returns true<br />

An alternative form enables or disables the flags until the end of the enclosing subpattern<br />

or pattern:<br />

preg_match('/I like (?i)<strong>PHP</strong>/', 'I like pHp'); // returns true<br />

preg_match('/I (like (?i)<strong>PHP</strong>) a lot/', 'I like pHp a lot', $match);<br />

// $match[1] is 'like pHp'<br />

Inline flags do not enable capturing. You need an additional set of capturing parentheses<br />

do that.<br />

Lookahead and Lookbehind<br />

It’s sometimes useful in patterns to be able to say “match here if this is next.” This is<br />

particularly common when you are splitting a string. The regular expression<br />

describes the separator, which is not returned. You can use lookahead to make sure<br />

(without matching it, thus preventing it from being returned) that there’s more data<br />

after the separator. Similarly, lookbehind checks the preceding text.<br />

Lookahead and lookbehind come in two forms: positive and negative. A positive lookahead<br />

or lookbehind says “the next/preceding text must be like this.” A negative lookahead<br />

or lookbehind says “the next/preceding text must not be like this.” Table 4-14<br />

shows the four constructs you can use in Perl-compatible patterns. None of the constructs<br />

captures text.<br />

Table 4-14. Lookahead and lookbehind assertions<br />

Construct Meaning<br />

(?=subpattern) Positive lookahead<br />

(?!subpattern) Negative lookahead<br />

(?

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

Saved successfully!

Ooh no, something went wrong!