Regex Tutorial

Learn regular expressions from the ground up. This tutorial assumes no prior knowledge and introduces one concept at a time, building on what you just learned.

Most examples use plain PHP’s preg_match() to show matches, but the concepts you’ll learn apply to almost any regex flavor that uses PCRE.

Examples marked with a Run button execute right here in the page: pick a PHP version beside the example, press Run, and the output appears under it with the engine that produced it — PHP and the PCRE2 build it bundles. PCRE2 (Perl Compatible Regular Expressions) is the regular expression engine PHP ships with. Nothing is sent to a server; the engine is downloaded once, only when you actually run something.

What You’ll Learn

1 · Regex basics

Write your first literal patterns.

6 min

2 · Character classes & escapes

Match sets of characters.

9 min

3 · Anchors & boundaries

Control where matches occur.

7 min

4 · Quantifiers & greediness

Control repetition.

8 min

5 · Groups & alternation

Capture and choose.

4 min

6 · Lookarounds & assertions

Match context without consuming.

8 min

7 · Backreferences & recursion

Match repeated or nested patterns.

7 min

8 · Performance & ReDoS

Write safe, fast patterns.

5 min

9 · Testing & debugging

Find and fix issues.

7 min

10 · Real-world PHP

Apply regex in practical PHP code.

7 min


Before You Start

Prerequisites

  • PHP 8.1 or newer — PCRE2 is built into PHP, so you already have everything you need for the engine
  • The mbstring extension — only needed for a few Unicode examples later on

You don’t need to install any extra packages to follow chapters 1–7. Just read, think, and test with preg_match() in your editor or REPL.

How to Use This Tutorial

  1. Go in order. Each chapter builds on the previous one.
  2. Read actively. Focus on understanding why, not just memorizing.
  3. Do the exercises. They’re short on purpose and use only what you’ve just learned.
  4. Look up as you go. If a term is mentioned, follow its link to learn it at the right time.
  5. Test for yourself. Copy an example and tweak it slightly. That’s often the fastest way to learn.

Start Here

Chapter 1: Regex Basics


Optional: Tools to Inspect Patterns

If you’d like a second opinion on a pattern you’re working on, you can use tools to explain or visualize it. These are completely optional — you can safely skip them and come back later.

PHPRegex CLI

Unlike the chapters themselves, these commands need the PHPRegex CLI installed in your project (vendor/bin/regex only exists after composer require and install). The Quick Start walks you through it.

vendor/bin/regex explain '/cat/i'
vendor/bin/regex diagram '/cat/i'
vendor/bin/regex validate '/cat/i'

PHPRegex API

use PHPRegex\Toolkit\Regex;

$regex = Regex::create();

$result  = $regex->validate('/cat/i');
$explain = $regex->explain('/cat/i');

Edit on GitHub Feedback