Lab 11: Advanced Regular Expressions

Objective

Master PHP's PCRE regex engine: named capture groups, non-greedy quantifiers, lookahead/lookbehind assertions, backreferences, preg_replace_callback, Unicode properties, and building a regex-powered template engine and log parser.

Background

PHP uses the PCRE2 library (Perl-Compatible Regular Expressions). Beyond simple pattern matching, PCRE supports named groups (?P<name>...), lookahead (?=...) / lookbehind (?<=...), atomic groups (?>...), and Unicode character classes \p{Lu} (uppercase letters). preg_replace_callback enables complex substitutions where the replacement depends on the match content.

Time

25 minutes

Prerequisites

  • PHP Foundations Lab 06 (Strings & Regex)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Named groups, lookahead, preg_replace_callback


Step 2: Template engine + log parser

📸 Verified Output:


Summary

Feature
Pattern
Notes

Named group

(?P<name>...)

Access via $m["name"]

Positive lookahead

(?=...)

Match if followed by

Negative lookahead

(?!...)

Match if NOT followed by

Lookbehind

(?<=...)

Match if preceded by

Non-greedy

*? +?

Match as little as possible

preg_replace_callback

fn receives match array

Complex replacements

Further Reading

Last updated