PHP Advent

#[Language]

PHP preg_match: Matching, Extraction, and Replace

By Rodney Renner ·

A dark mahogany engraver bench lit by a warm brass desk lamp holds a blank brass stencil ruler, cylindrical steel punches in a drilled wooden block, and a roll of perforated paper tape beside an open grid notebook.

In PHP, preg_match($pattern, $subject, $matches) tests a string against a regular expression and captures the first match. Use preg_match_all() to extract every match, or preg_replace() to replace matching text. Each pattern needs matching single-byte delimiters such as /.../ or #...#. Add the /u modifier for UTF-8 text.

Check the return value of preg_match() with strict comparisons: === 1 means a match, === 0 means no match, and === false means an engine error. A loose comparison loses that distinction.

Skip regular expressions when a simpler built-in function fits the job. Use [str_contains()](/articles/php-string-contains), str_starts_with(), or str_ends_with() for literal substring checks, str_replace() for fixed text replacements, and [DateTimeImmutable::createFromFormat()](/articles/php-date-format) to validate real calendar dates. The examples target PHP 8.0 and later. Features introduced in PHP 8.2 or 8.4 are noted where they appear.

Delimiters, Modifiers, and Escaping with preg_quote()

PHP's PCRE functions use delimiters to separate the pattern from its single-letter modifiers. According to the PHP delimiters reference, a delimiter can be any single-byte character that is not alphanumeric, a backslash, whitespace, or a NUL byte. Multi-byte characters such as § fail because PHP reads only the first byte as the delimiter and tries to parse the remaining bytes as pattern modifiers.

Forward slashes (/pattern/) are the usual choice. For paths or URLs, hash signs (#pattern#) or tildes (~pattern~) save you from escaping each slash. You can also use paired brackets ({}, (), [], <>), though unmatched brackets inside character classes such as {[}]} still require backslash escaping because PCRE stops scanning for the closing delimiter when it hits }.

Before and After: Choosing Readable Delimiters

When matching URL routes or filesystem paths, switching away from / removes clutter without changing what the pattern matches:

<?php

$path = '/api/v2/invoices/4089';

// Before: slashes inside the pattern must be escaped
$matchedOld = preg_match('/^\/api\/v\d+\/invoices\/(\d+)$/', $path, $matches);

// After: hash delimiters leave path slashes literal
$matchedNew = preg_match('#^/api/v\d+/invoices/(\d+)$#', $path, $matches);

Both patterns compile to the same matcher, and $matches[1] holds '4089' in both cases.

Two brass-bound oak framing jigs on a dark workbench contrast a ribbon crossed by steel pins on the left with an unobstructed cream ribbon held between parallel brass brackets on the right.

Escaping Dynamic Input with preg_quote()

Escape user input and configuration strings before adding them to a pattern. Pass these fragments through preg_quote(string $str, ?string $delimiter = null): string first so regex metacharacters (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #) are escaped as literals.

Pass your delimiter as the second argument. / is absent from preg_quote()'s default list of regex metacharacters. Without that argument, literal slashes stay unescaped inside /.../ patterns:

<?php

$prefix = '/v1.0/export';
$uri = '/v1.0/export/daily-report';

$escaped = preg_quote($prefix, '#');
// Result: '/v1\.0/export' ('.' is escaped, while '/' stays literal)

$pattern = '#^' . $escaped . '/[a-z0-9-]+$#';

if (preg_match($pattern, $uri) === 1) {
    // Matches safely even though $prefix contains '.' and '/'
}

Use preg_quote() only when building the $pattern argument. Do not run it on the $replacement string of preg_replace(), because backslashes before ordinary characters are preserved as literal backslashes in replacements.

Validating Strings and Checking === 1 Versus 0 Versus false

The PHP preg_match manual defines preg_match() with five parameters:

preg_match(
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
): int|false

preg_match() stops after the first match. Its return value tells you what happened:

  • 1 when the pattern matches $subject.
  • 0 when the pattern is valid and $subject does not match.
  • false when PCRE encounters an error, such as an invalid pattern (E_WARNING), malformed UTF-8 under /u, or hitting pcre.backtrack_limit or pcre.recursion_limit.

Before and After: Distinguishing Non-Matches from Errors

A loose truthy or falsy check hides PCRE engine failures by treating false the same as 0:

<?php

// Before: a backtrack limit error or invalid UTF-8 input silently looks like "no match"
function isValidTokenUnsafe(string $token): bool
{
    return (bool) preg_match('/^[a-z0-9_-]{12,64}$/', $token);
}

// After: explicit strict check surfaces engine failures via preg_last_error_msg()
function isValidToken(string $token): bool
{
    $result = preg_match('/^[a-z0-9_-]{12,64}\z/', $token);

    if ($result === false) {
        throw new RuntimeException(
            'Regex evaluation failed: ' . preg_last_error_msg()
        );
    }

    return $result === 1;
}

Two details changed in the safer version. First, checking $result === false before returning $result === 1 ensures 0 returns false cleanly while an engine failure raises an exception with preg_last_error_msg(), introduced in PHP 8.0 (PHP preg_last_error_msg manual). Before PHP 8.0, you had to map the integer from preg_last_error() against PREG_* constants yourself.

Second, the anchor at the end changed from $ to \z. By default in PCRE, $ matches either at the very end of the string or right before a trailing \n character. Using \z (or adding the /D PCRE_DOLLAR_ENDONLY modifier) rejects "abc123456789\n" during strict input validation.

Inspecting Backtrack and UTF-8 Failures

Calling preg_last_error_msg() returns "No error" when the previous regex call succeeded, or a descriptive message such as "Backtrack limit exhausted" when catastrophic backtracking hits pcre.backtrack_limit:

<?php

$result = preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if ($result === false && preg_last_error() !== PREG_NO_ERROR) {
    // Outputs: Error: Backtrack limit exhausted
    echo 'Error: ' . preg_last_error_msg() . PHP_EOL;
}

preg_last_error() also lets you compare the error code with constants such as PREG_BACKTRACK_LIMIT_ERROR.

For untrusted input, use simple non-overlapping quantifiers or possessive quantifiers (++, *+). These let malicious strings fail quickly without exhausting the backtrack budget.

Extracting Structured Values with Named Capture Groups

Adding an optional prefix group to a pattern can change what $matches[1] and $matches[2] refer to. Named capture groups give you string keys in $matches instead. Write them as (?<name>...) or (?P<name>...).

After a successful match, $matches contains both the named key and the numeric group index. It is a one-dimensional list unless you set PREG_OFFSET_CAPTURE:

<?php

$tag = 'v2.14.3-rc.1';
$pattern = '/^v(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[a-z0-9.]+))?\z/';

$matched = preg_match($pattern, $tag, $matches, PREG_UNMATCHED_AS_NULL);

if ($matched === 1) {
    $version = [
        'major' => (int) $matches['major'],
        'minor' => (int) $matches['minor'],
        'patch' => (int) $matches['patch'],
        'prerelease' => $matches['prerelease'], // null when omitted, not missing or ''
    ];
}

The optional prerelease label needs two details:

  1. (?:-(?<prerelease>...))? wraps the hyphen and label in a non-capturing group (?:...) so the hyphen is not stored separately in $matches.
  2. PREG_UNMATCHED_AS_NULL guarantees that $matches['prerelease'] exists and equals null when $tag is 'v2.14.3'. Without PREG_UNMATCHED_AS_NULL, PHP omits trailing unmatched groups from $matches entirely and turns earlier unmatched groups into empty strings ''. Using PREG_UNMATCHED_AS_NULL (supported since PHP 7.2, and for trailing groups in preg_match() since PHP 7.4) gives static analyzers like PHPStan a predictable array shape.
A dark walnut sorting board on a workbench holds three graduated brushed-steel cylinders seated in brass-rimmed circular pockets while the fourth optional pocket sits cleanly empty.

Filtering Numeric Duplicates and Using /n in PHP 8.2+

To keep only named captures, filter out the numeric keys (0, 1, 2) after matching:

<?php

$namedOnly = array_filter($matches, is_string(...), ARRAY_FILTER_USE_KEY);

The first-class callable is_string(...) requires PHP 8.1 or later; on PHP 8.0, pass 'is_string'.

PHP 8.2 and later support the /n (PCRE_NO_AUTO_CAPTURE) modifier. With it, plain parentheses (...) behave like non-capturing groups; only named groups capture. On PHP 8.4 and later (which bundles PCRE2 10.44), subpattern names can be up to 128 characters long, up from 32 characters in older PHP releases.

Extracting Every Match with preg_match_all()

Use preg_match_all() to extract multiple records, tokens, or tags from a string. As described in the PHP preg_match_all manual, it scans the entire subject for non-overlapping matches. It returns the total count of full matches (int, including 0) or false on error. The results go into a multidimensional $matches array.

PREG_PATTERN_ORDER Versus PREG_SET_ORDER

The fourth parameter $flags determines how $matches is nested:

  • PREG_PATTERN_ORDER (the default) groups results by capture group: $matches[0] holds all full matches, $matches['key'] holds all captures for group key, and so on.
  • PREG_SET_ORDER groups results by match occurrence: $matches[0] is the first complete match array, $matches[1] is the second complete match array, and each entry has its own named and numbered keys.

Use PREG_SET_ORDER when each match is a record with several fields and you want to process the records in a foreach loop:

<?php

$logLine = 'method=POST status=201 duration_ms=42 path=/orders';
$pattern = '/(?<key>[a-z_]+)=(?<value>\S+)/';

$count = preg_match_all(
    $pattern,
    $logLine,
    $matches,
    PREG_SET_ORDER | PREG_UNMATCHED_AS_NULL
);

if ($count === false) {
    throw new RuntimeException(preg_last_error_msg());
}

$fields = [];
foreach ($matches as $match) {
    $fields[$match['key']] = $match['value'];
}
// $fields is ['method' => 'POST', 'status' => '201', 'duration_ms' => '42', 'path' => '/orders']

Use PREG_PATTERN_ORDER for a flat list from one capture group. You can read $matches['id'] directly, without looping over the match records.

Byte Offsets with PREG_OFFSET_CAPTURE

Add PREG_OFFSET_CAPTURE (combined via bitwise |) when you need to know where each match started in $subject. Every captured value becomes a two-element array [string $text, int $byteOffset]. Both $byteOffset and the fifth parameter $offset on preg_match() and preg_match_all() count bytes, even with /u. If $offset lands in the middle of a multi-byte UTF-8 character under /u, PCRE fails with PREG_BAD_UTF8_OFFSET_ERROR.

Transforming Strings with preg_replace() and Callbacks

The PHP preg_replace manual gives preg_replace() the signature:

preg_replace(
    string|array $pattern,
    string|array $replacement,
    string|array $subject,
    int $limit = -1,
    int &$count = null
): string|array|null

For a string $subject, preg_replace() returns a string on success or null on error. With zero matches, it returns the original string. If $subject is an array of strings, it runs on every element, preserves associative keys, and returns an array or null.

Backreferences, Limits, and Error Checking

Inside $replacement, $0 refers to the entire match and $1 through $99 refer to numbered capture groups. When a backreference is followed immediately by a literal digit, wrap the group number in braces (${1}0) so PHP does not read $10 as the tenth capture group:

<?php

$raw = 'Order #42 and Order #108';
$updated = preg_replace('/#(\d+)/', '#${1}0', $raw, -1, $replacements);

if ($updated === null) {
    throw new RuntimeException('Replace failed: ' . preg_last_error_msg());
}
// $updated === 'Order #420 and Order #1080', $replacements === 2

Pass a positive integer to $limit (default -1 for unlimited) to cap replacements per pattern per string, and pass a variable to &$count to inspect how many substitutions occurred. Check $updated === null before passing the result to another string operation. Replacement errors return null, rather than false.

Passing Pattern and Replacement Arrays Safely

Pass parallel arrays to $pattern and $replacement to run several rules in sequence. PHP reads these arrays in insertion order, so their numeric keys may be misleading. If $patterns[2] was inserted before $patterns[0], preg_replace() pairs elements by insertion position rather than matching key 0 to key 0. Call ksort() on both arrays if keys were assigned out of order, or keep both arrays as synchronized lists (array_values()).

Stepping Up to preg_replace_callback()

Replacement strings in preg_replace() support numbered backreferences ($0..$99 or \0 through \99), but cannot refer to named groups such as $matches['name'] or $matches['key']. Use preg_replace_callback() when you need named groups, conditional logic, escaping, or value formatting:

<?php

$template = 'Hello {{ user_name }}, balance: {{ amount }}';

$rendered = preg_replace_callback(
    '/\{\{\s*(?<key>[a-z_]+)\s*\}\}/',
    static function (array $matches): string {
        $values = ['user_name' => 'Amina', 'amount' => '$48.00'];
        return $values[$matches['key']] ?? '';
    },
    $template
);

if ($rendered === null) {
    throw new RuntimeException(preg_last_error_msg());
}
// $rendered === 'Hello Amina, balance: $48.00'

For several patterns with separate callbacks, pass an associative array of pattern => callable pairs to preg_replace_callback_array().

Handling UTF-8 Safely with the /u Modifier

Without the /u (PCRE_UTF8) modifier, PCRE treats both the pattern and the subject as raw single-byte streams. That breaks multi-byte UTF-8 text in three ways:

  1. Quantifiers and . count bytes instead of Unicode code points, so /^.{3}$/ rejects "café" (4 code points, 5 UTF-8 bytes) and accepts the single character "€" (3 UTF-8 bytes).
  2. Character classes like [äöü] split multi-byte characters into separate bytes and can match unrelated UTF-8 sequences that happen to share a byte.
  3. Unicode property escapes such as \p{L} (letters) or \p{N} (numbers) do not work as expected without UTF-8 and Unicode property support.

Appending /u switches PCRE into UTF-8 mode, as noted in the PHP pattern modifiers reference. In PHP's PCRE2 integration, it also enables Unicode character properties (PCRE2_UCP):

<?php

$city = 'Zürich';

// Without /u: \w matches ASCII [A-Za-z0-9_] only -> returns 0
$asciiOnly = preg_match('/^\w+\z/', $city);

// With /u: \w and \p{L} recognize Unicode letters -> returns 1
$unicodeMatch = preg_match('/^\p{L}+\z/u', $city);

With /u, shorthand classes such as \d and \w also expand beyond ASCII. \w matches letters and digits across Unicode scripts, plus combining marks and connector punctuation in PHP 8.4+. Under /u, \d matches Unicode decimal digits (\p{Nd}, such as Arabic-Indic digits) rather than only ASCII 0-9. When validating an ASCII-only integer or code under /u, write [0-9] instead of \d.

Two wooden measuring tracks on a dark workbench contrast evenly spaced brass divider blades slicing across an amber glass slab on the left with an adjustable brass frame holding three whole amber glass tiles of different widths on the right.

Catching Invalid UTF-8 Inputs

Under /u, PCRE checks the UTF-8 encoding of both the pattern and the subject. The failure behavior differs:

  • An invalid UTF-8 byte sequence in the pattern triggers an E_WARNING and causes the function to return false (null for preg_replace()).
  • An invalid UTF-8 byte sequence in the subject does not emit a warning. Instead, the function silently fails (false or null) and sets preg_last_error() to PREG_BAD_UTF8_ERROR (preg_last_error_msg() returns "Malformed UTF-8 characters, possibly incorrectly encoded").

Validate untrusted strings with mb_check_encoding($input, 'UTF-8') at your application boundary (similar to guarding malformed input in [json_decode()](/articles/php-json-decode)), and always check === false or === null after running /u patterns.

On PHP 8.4 and later, you can combine /u and /i with /r (PCRE2_EXTRA_CASELESS_RESTRICT) to stop case-insensitive matching from crossing between ASCII and non-ASCII characters (for example, preventing 'K' from matching the Kelvin sign U+212A).

Common PHP Regex Mistakes to Avoid

  • **Using preg_match() for fixed substrings:** Checking preg_match('/error/', $log) invokes the PCRE engine unnecessarily when str_contains($log, 'error') is clearer and avoids pattern escaping.
  • **Validating whole strings with $ instead of \z:** Because $ allows a single trailing \n before end-of-string, /^\d+$/ matches "42\n". Always use \z or the /D modifier on input validators.
  • **Forgetting the $delimiter argument in preg_quote():** Calling preg_quote($url) without passing '/' as the delimiter leaves any / in the runtime string unescaped, which can cause a PCRE compilation warning when / delimits the pattern.
  • **Assuming preg_replace() always returns a string:** A backtrack failure or invalid UTF-8 input returns null. Under declare(strict_types=1);, passing that result straight into a string-typed function triggers a TypeError.
  • Mixing byte offsets with UTF-8 strings: Both $offset and PREG_OFFSET_CAPTURE operate on byte indices, never character counts. Slice strings with substr(), not mb_substr(), when working with offsets returned by PCRE.