Repetition and Quantifiers

Part of a pattern may or may not be present, or may be repeated a number of times. This is referred to as repetition and involves using meta-characters collectively referred to as quantifiers.

<?php
// Matches 'a' 0 times or 1 time if present
$matches = (preg_match('/a?/', $string) == 1);

// Matches 'a' 0 or more times, however many that may be
$matches = (preg_match('/a*/', $string) == 1);

// Matches 'a' 1 or more times, however many that may be
$matches = (preg_match('/a+/', $string) == 1);

// Matches 'a' 0 times or 1 time if present, same as?
$matches = (preg_match('/a{0,1}/', $string) == 1);

// Matches 'a' 0 or more times, same as *
$matches = (preg_match('/a{0,}/', $string) == 1);

// Matches 'a' 1 or more times, same as +
$matches = (preg_match('/a{1,}/', $string) == 1);

// Matches 'a' exactly 2 times
$matches = (preg_match('/a{2}/', $string) == 1);
?>

Note that any use of curly brackets that is not of the form {X}, {X,}, or {X,Y} will be treated as a literal string within the pattern.


© PCRE Extension — Web Scraping

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