O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Quantifiers

A quantifier is a metacharacter that tells "how many." You put a quantifier after an item to indicate you want to match that item a certain number of times. Quantifiers are listed in Table B-1.

Table B-1. Quantifiers

Quantifier

How many times

*

Zero or more

+

One or more

?

Optional (zero or one)

{ x}

Exactly x

{ x,}

At least x

{ x,y}

At least x, but no more than y

To use a quantifier, put it immediately after the item you want to quantify. Table B-2 shows some regular expressions with quantifiers.

Table B-2. Quantifier examples

Regular expression

Meaning

Matches

Doesn't match

ba+

b, then at least one a

ba, baa, baaa, rhumba, babar

b, abs, taaa-daaa, celeste

ba+na*s

b, at least one a, n, zero or more a, s

turbans, baanas, rhumbanas!

banana, bananas

ba(na){2}

ba, then na twice

banana, bananas, semi-banana, bananarama

cabana, banarama

ba{2,}ba{3,}

b, then at least two a, then b, then at least three a

baabaaa, baaaaabaaaaa, rhumbaabaaas

baabaa, babaaar, banana

(baa-){2,4}baa

baa- at least two, but not more than four times, then baa

baa-baa-baa, baa-baa-baa-baa-baa, oomp-pa-pa-baa-baa-baa-oomp-pa-pa

baa-baa, baa-baad-news

dogs? and cats?( and chickens?)?

dog, then an optional s, then and cat, then an optional s, then an optional and chicken or and chickens

dog and cat and chicken, dog and cat and chickens, hotdogs and cats, dogs and cat and chickens, dog and cats and chicken ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required