Skip to main content

Lesson 6 of 8

Regular Expressions - preg_match, preg_replace & preg_split

Regular expressions are patterns for matching, extracting, and replacing text. PHP uses PCRE (Perl Compatible Regular Expressions) - the most powerful and widely-used regex engine. They're essential for input validation (email, phone, URL), slug generation, log parsing, and extracting data from arbitrary text.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Regex in PHP - Practical Patterns

Regex in PHP - Practical Patterns
<?php
declare(strict_types=1);

// ── preg_match - does pattern match? ─────────────────────────
// Returns 1 (match), 0 (no match), false (error)
// $matches[0] = full match, $matches[1] = first capture group

// Validate email (simplified - use filter_var for production)
$email = "alice@example.com";
if (preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/', $email)) {
    echo "Valid email";
}

// Extract version from string
$version = "PHP/8.3.1";
if (preg_match('/PHP/(d+).(d+).(d+)/', $version, $matches)) {
    echo "Major: {$matches[1]}, Minor: {$matches[2]}";  // Major: 8, Minor: 3
}

// Named capture groups (much cleaner)
$dateStr = "2026-03-20";
if (preg_match('/(?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2})/', $dateStr, $m)) {
    echo "Year: {$m['year']}, Month: {$m['month']}";    // Year: 2026, Month: 03
}

// ── preg_match_all - find ALL matches ─────────────────────────
$html = '<a href="https://php.net">PHP</a> and <a href="https://laravel.com">Laravel</a>';
preg_match_all('/<a href="([^"]+)">([^<]+)</a>/', $html, $matches);
$urls  = $matches[1];   // ["https://php.net", "https://laravel.com"]
$texts = $matches[2];   // ["PHP", "Laravel"]

// ── preg_replace - search and replace ─────────────────────────
// Remove all HTML tags
$clean = preg_replace("/<[^>]+>/", "", $html);   // "PHP and Laravel"

// Normalise whitespace
$normalised = preg_replace("/s+/", " ", "Hello   World  PHP");  // "Hello World PHP"

// Slug generation
function makeSlug(string $title): string {
    $slug = mb_strtolower(trim($title));
    $slug = preg_replace("/[^a-z0-9-]+/", "-", $slug);
    return trim($slug, "-");
}
echo makeSlug("Hello, World! PHP 8.x");  // "hello-world-php-8-x"

// ── preg_split - split by pattern ─────────────────────────────
$words = preg_split("/[s,;]+/", "php, web; backend  api");
// ["php", "web", "backend", "api"]

// ── Common validation patterns ────────────────────────────────
$patterns = [
    "phone"    => '/^+?[1-9]d{7,14}$/',
    "username" => '/^[a-zA-Z0-9_]{3,20}$/',
    "password" => '/^(?=.*[A-Z])(?=.*d)(?=.*[^A-Za-z0-9]).{8,}$/',
    "slug"     => '/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
    "ipv4"     => '/^(d{1,3}.){3}d{1,3}$/',
];

// ✅ Safer: Use filter_var for standard formats - no regex needed
filter_var("alice@example.com", FILTER_VALIDATE_EMAIL);  // validated email
filter_var("192.168.1.1",       FILTER_VALIDATE_IP);     // validated IP
filter_var("https://php.net",   FILTER_VALIDATE_URL);     // validated URL

Quick Quiz

Tip

Tip

Practice Regular Expressions pregmatch pregreplace pregsplit in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Regular Expressions - preg_match, preg_replace & preg_split

Practice Task

Note

Practice Task - (1) Write a working example of Regular Expressions pregmatch pregreplace pregsplit from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Regular Expressions pregmatch pregreplace pregsplit is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done