Subpatterns

You’ll notice in the examples from the previous section that only a single character was used. This is because the concept of subpatterns hadn’t been introduced yet. To understand these, it’s best to look an example that doesn’t use them in order to understand the effect they have on how the pattern matches.

<?php
// Matches 'a' follow by one or more instances of 'b'
$matches = (preg_match('/ab+/', $string) == 1);
?>

Without subpatterns there would be no way to match, for example, one or more instances of the string 'ab’. Subpatterns solve this pattern by allowing individuals parts of a pattern to be grouped using parentheses.

<?php
// Matches 'ab' one or more times
$matches = (preg_match('/(ab)+/', $string) == 1);

// Matches 'foo' or 'foobar'
$matches = (preg_match('/foo(bar)?/', $string) == 1);

// Matches 'ab' or 'ac'
$matches = (preg_match('/a(b|c)/', $string) == 1);

// Matches 'ab', 'ac', 'abb', 'abc', 'acb', 'acc', etc.
$matches = (preg_match('/a(b|c)+/', $string) == 1);
?>

© PCRE Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (03.09.2014)
Views: 384 | Rating: 0.0/0
Total comments: 0
avatar