CodeBlanks Logo Icon CodeBlanks

Quantifiers

PHP course · Advanced · Lesson 45/92

Learn to specify repetition with *, +, ? and {}.

Quantifiers: *, +, ?, {n}

A quantifier tells how many times an item repeats. The four most common ones:

* zero or more. The pattern ab*c matches ac, abc, abbbbc.

+ one or more. ab+c requires at least one b, so it does not match ac.

? zero or one (optional). ab?c matches both ac and abc.

{n,m} between n and m repetitions. a{2,4} means 2 to 4 as.

Greedy and lazy matching

Quantifiers are greedy by default: they take the longest possible match. The pattern /".+"/ takes all text between the first and the last quote as a single piece.

You can make them lazy by adding a question mark: /".+?"/ takes the shortest match, i.e. the first "..." pair.

When extracting content between quotes or tags, lazy matching is usually safer.

Exercise Validate a phone format

Write isPhoneNumber(string $str): bool. Validate the 05XX XXX XX XX format with the pattern /^05\d{2}\s\d{3}\s\d{2}\s\d{2}$/; return true on match, false otherwise. Compare the preg_match result with === 1. The three echo calls below are already written.

Show example solution
bool { return preg_match("/^05\d{2}\s\d{3}\s\d{2}\s\d{2}$/", $str) === 1; }
Example solution:
<?php
// isPhoneNumber: validate 05XX XXX XX XX format with quantifiers

// Define the isPhoneNumber function
function isPhoneNumber(string $str): bool {
    return preg_match("/^05\d{2}\s\d{3}\s\d{2}\s\d{2}$/", $str) === 1;
}

echo isPhoneNumber("0555 123 45 67") ? "valid\n" : "invalid\n";
echo isPhoneNumber("12345") ? "valid\n" : "invalid\n";
echo isPhoneNumber("0555 123 45 6") ? "valid\n" : "invalid\n";

Test yourself

  1. One or more digits

    $pattern = "/\d____/";
    preg_match($pattern, "Tel: 0555", $matches);
    Show answer
    $pattern = "/\d+/";
    preg_match($pattern, "Tel: 0555", $matches);
  2. Quantifier meanings

    *
    Zero or more
    +
    One or more
    ?
    Zero or one
    {2,4}
    Between two and four
  3. In the pattern a*b, what does * mean?

    • Exactly one 'a'
    • At least one 'a'
    • Zero or more 'a's
    • Zero or one 'a'
    Show answer

    Zero or more 'a's — Correct. * means zero or more repetitions.

All lessons in Advanced