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.
2 · Character classes & escapes
Match sets of characters.
3 · Anchors & boundaries
Control where matches occur.
4 · Quantifiers & greediness
Control repetition.
5 · Groups & alternation
Capture and choose.
6 · Lookarounds & assertions
Match context without consuming.
7 · Backreferences & recursion
Match repeated or nested patterns.
8 · Performance & ReDoS
Write safe, fast patterns.
9 · Testing & debugging
Find and fix issues.
10 · Real-world PHP
Apply regex in practical PHP code.
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
mbstringextension — 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
- Go in order. Each chapter builds on the previous one.
- Read actively. Focus on understanding why, not just memorizing.
- Do the exercises. They’re short on purpose and use only what you’ve just learned.
- Look up as you go. If a term is mentioned, follow its link to learn it at the right time.
- Test for yourself. Copy an example and tweak it slightly. That’s often the fastest way to learn.
Start Here
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');