0Pricing
PHP Academy · Lesson

Matching with preg_match

Test strings against patterns and capture groups.

Matching with preg_match is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

preg_match() Signature

preg_match($pattern, $subject, &$matches) returns 1 if the pattern matches, 0 if it does not, or false on error.

Simple Match Test

Use preg_match as a boolean test — return value 1 means found.

<?php
$email = "user@example.com";
if (preg_match('/\w+@\w+\.\w+/', $email)) {
    echo "Looks like an email";
}

Capturing Groups with $matches

$matches[0] is the full match; $matches[1], $matches[2]... are capture groups.

<?php
preg_match('/^(\w+)\s(\w+)$/', "John Smith", $m);
echo $m[1]; // "John"
echo $m[2]; // "Smith"

Named Captures

Use (?P<name>...) for named capture groups — accessed as $matches["name"].

<?php
preg_match('/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/',
           '2025-06-15', $m);
echo $m['year'];  // 2025

Offset Parameter

The 4th parameter specifies where in the string to start matching (byte offset).

<?php
preg_match('/\d+/', 'abc123def456', $m, 0, 3);
echo $m[0]; // "123"

PREG_OFFSET_CAPTURE

Get both the match value and its byte offset.

<?php
preg_match('/\d+/', "price: 42 USD", $m, PREG_OFFSET_CAPTURE);
echo $m[0][0]; // "42"
echo $m[0][1]; // 7 (byte offset)

preg_match_all()

preg_match_all() finds all matches and returns the count.

<?php
$html = '<a href="a.com">A</a> <a href="b.com">B</a>';
preg_match_all('/<a href="([^"]+)">/', $html, $m);
print_r($m[1]); // ["a.com", "b.com"]

Email Validation Example

A practical email regex:

<?php
function isEmail(string $s): bool {
    return (bool) preg_match(
        '/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/',
        $s
    );
}

Phone Validation

Validate international phone numbers:

<?php
preg_match('/^\+?[1-9]\d{7,14}$/', '+1234567890', $m);

Handling Errors

If the pattern is invalid, preg_match() returns false. Check with === false and use preg_last_error() for details.

Performance Tip

PHP caches compiled PCRE patterns internally — if you use the same regex in a loop, no extra steps are needed.

When Not to Use Regex

For structured data, PHP has dedicated functions: filter_var(FILTER_VALIDATE_EMAIL), parse_url() — prefer these over hand-rolled regex.

Quick Check

What does $matches[0] contain after preg_match?

Frequently asked questions

Is the “Matching with preg_match” lesson free?

Yes — the full text of “Matching with preg_match” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Matching with preg_match”?

Test strings against patterns and capture groups. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Matching with preg_match” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Regex Syntax Fundamentals
  2. Matching with preg_match
  3. Replacing Text with preg_replace
  4. Splitting and Practical Patterns
← Back to PHP Academy