CodeBlanks Logo Icon CodeBlanks

Matching with preg_match()

PHP course · Advanced · Lesson 41/92

Learn to match a pattern in a string with preg_match().

What are regular expressions (regex)?

Regular expressions (regex) are a small but powerful language for searching patterns inside text. In PHP, regex patterns are written between two delimiters; the most common delimiter is the slash: /apple/.

To match a pattern against text you use preg_match($pattern, $subject, $matches). It returns 1 if a match is found, 0 otherwise; the matched piece is written into the $matches array.

Inside a pattern, letters and digits match themselves; special characters carry meaning.

preg_match parameters and $matches

preg_match takes three main parameters: the pattern, the text to search, and the array to hold matches. The third parameter, $matches, is optional but used most of the time.

If a match is found, $matches[0] holds the whole matched piece. If the pattern uses parentheses for capture groups, $matches[1], $matches[2] hold the groups in order.

If no match is found, the array stays empty. Since the return value is numeric, the if (preg_match(...)) idiom is common.

Exercise Find the first digit

In the string $phone = "Tel: 0555 123 45 67";, use preg_match to find the first digit. Put the pattern into $pattern, the result into $matches, and print $matches[0] on a new line.

Show example solution
Set the pattern to "/\d/". Call preg_match($pattern, $phone, $matches). Print with echo $matches[0] . "\n";
Example solution:
<?php
// Find the first digit with preg_match

$phone = "Tel: 0555 123 45 67";
// Set the pattern and matches variable
$pattern = "/\d/";
preg_match($pattern, $phone, $matches);

// Print the first match
echo $matches[0] . "\n";

Test yourself

  1. What does preg_match return?

    • It returns the matched text itself
    • It returns 1 if matched, 0 if not
    • It always returns true
    • It returns the index of the first match
    Show answer

    It returns 1 if matched, 0 if not — Correct. preg_match returns 1 on match, 0 on no match, false on error.

  2. Add delimiters to the pattern

    $pattern = "____";
    echo preg_match($pattern, "apple pie") . "\n";
    Show answer
    $pattern = "/apple/";
    echo preg_match($pattern, "apple pie") . "\n";
  3. Understand the regex pieces

    /.../
    Regex delimiters
    $matches
    Array holding the matches
    preg_match
    Function that finds the first match
    1 or 0
    preg_match return value

All lessons in Advanced