Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 147 ยท Strings in Depth

Regular Expressions

Learn PCRE regular expressions in PHP - preg_match, preg_match_all, preg_replace, callbacks, preg_split, named groups, flags, preg_quote and how to avoid ReDoS.

A regular expression (regex) is a small pattern language for describing text: "four digits, a dash, two digits", "a word that starts with a capital letter", "any run of spaces and tabs". With one pattern you can check whether input looks right, pull values out of a log line, or rewrite every date in a document.

PHP uses PCRE (Perl Compatible Regular Expressions), the same flavor found in many languages and tools, through a family of functions that all start with preg_. This lesson teaches the pattern syntax you'll use every day, then each function in turn: matching, finding all matches, replacing, replacing with a callback and splitting. It finishes with the safety topics professionals care about: escaping user input in patterns, Unicode and catastrophic backtracking.

If a plain function can do the job, prefer it. str_contains(), str_starts_with() and explode() from String Functions and Formatting Strings are faster and easier to read. Reach for a regex when the text has a shape rather than a fixed value.

Patterns, delimiters and modifiers

A PHP pattern is a string that begins and ends with a delimiter, usually /. Anything after the closing delimiter is a list of modifiers (flags):

PHP
$pattern = '/colou?r/i';
// "/" ... "/"  the delimiters around the pattern
// colou?r      the pattern: "colo", an optional "u", then "r"
// i            a modifier: match case-insensitively

Always write patterns in single quotes. In double quotes, PHP would interpret \n, \t and $name itself before the regex engine ever sees them.

If your pattern contains many slashes, such as a URL path, pick another delimiter: '#^/blog/\d+$#' or '~^/blog/\d+$~'. Any non-alphanumeric, non-whitespace character except backslash works, and brackets can be used as pairs: '{\d+}'.

The pattern language in one table

Syntax Matches
abc The literal text abc
. Any character except a newline
\d \w \s A digit, a word character ([A-Za-z0-9_]), whitespace
\D \W \S The opposites: not a digit, not a word character, not whitespace
[aeiou] [a-z0-9] One character from the set or range
[^0-9] One character not in the set
^ $ Start and end of the string (of each line with m)
\b A word boundary
* + ? 0 or more, 1 or more, 0 or 1 of the previous item
{2,5} {2,} Exactly 3, between 2 and 5, at least 2
a|b a or b
(โ€ฆ) A capturing group
(?:โ€ฆ) A group that doesn't capture
(?<name>โ€ฆ) A named capturing group
\. \( \$ A literal special character, escaped with a backslash

Quantifiers are greedy: they take as much as they can. Add ? to make one lazy (.*?, +?), taking as little as possible.

preg_match: does it match, and what did it capture?

preg_match($pattern, $subject, $matches) searches for the first match. It returns 1 if it found one, 0 if not, and false if the pattern itself is broken. The optional third argument receives the match: index 0 is the whole match, then one entry per capturing group.

PHP Validating and capturing with preg_match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the anchors. Without ^ and $, the pattern [A-Z]{2}-\d{4} would happily match inside 'XY-9876 extra'. When you validate input, anchor both ends.

Anchors: $ versus \z

There's one subtle trap: $ also matches just before a final newline. So '/^\d+$/' accepts "123\n". If a trailing newline would be a problem (for example a value pasted from a form), use \z, which only matches the true end of the string, or add the D modifier.

Named groups

Counting parentheses gets error-prone. A named group (?<name>โ€ฆ) puts the capture under a readable key, and also under its number:

PHP Named groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last part shows another detail. When an optional group at the end didn't participate, PHP leaves it out of $matches entirely. With the PREG_UNMATCHED_AS_NULL flag, it's present as null, which makes the array shape predictable.

preg_match_all: every match

preg_match_all() finds all non-overlapping matches and returns how many it found. By default the result is grouped by capture group (PREG_PATTERN_ORDER): $m[0] holds every full match, $m[1] every first group, and so on. With PREG_SET_ORDER, you get one array per match instead, which is usually what you want for looping.

PHP Finding every match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The email pattern here is deliberately simple. Real email validation is better done with filter_var($email, FILTER_VALIDATE_EMAIL), as you'll see in Form Validation.

preg_replace: search and replace by pattern

preg_replace($pattern, $replacement, $subject) replaces every match. In the replacement, $1, $2 (or ${1}) insert captured groups, and $0 inserts the whole match. Use ${1} when a digit follows the reference: ${1}0 means "group 1, then a zero", while $10 would mean group 10.

An optional fourth argument limits the number of replacements, and a fifth receives the count actually made. You can also pass arrays of patterns and replacements to apply several rules in order.

PHP Replacing with preg_replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The masking line uses a lookahead, (?=โ€ฆ): it checks that four digits follow without consuming them, so only digits that have at least four more after them are replaced. Lookbehind (?<=โ€ฆ) checks what comes before, and (?!โ€ฆ)/(?<!โ€ฆ) are the negative versions.

preg_replace_callback: computed replacements

When the replacement depends on logic, not just captured text, use preg_replace_callback(). PHP calls your function for each match, passing the $matches array, and uses the string you return.

PHP Replacements computed by a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The arrow function sees $values automatically; Anonymous Functions and Closures explains how that works.

preg_split and preg_grep

preg_split() is explode() with a pattern as the separator. The flag PREG_SPLIT_NO_EMPTY drops empty pieces, and PREG_SPLIT_DELIM_CAPTURE keeps captured separators in the result. preg_grep() filters an array, keeping the elements that match (and their keys).

PHP Splitting and filtering by pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Modifiers

Modifiers change how the whole pattern behaves. Combine them freely: '/โ€ฆ/imu'.

Modifier Effect
i Case-insensitive
m Multiline: ^ and $ match at the start and end of every line
s Dotall: . also matches newlines
u UTF-8 mode: the pattern and subject are treated as UTF-8 characters, not bytes
x Extended: whitespace in the pattern is ignored and # starts a comment
D $ matches only at the very end, never before a final newline
PHP The i, m, s, u and x modifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use u whenever your text may contain non-ASCII characters. Without it, . and [^โ€ฆ] can match half of a multibyte character, and preg_split('//', โ€ฆ) chops รฉ into two broken bytes. With u, invalid UTF-8 in the subject makes the function fail and return false, which is usually what you want: you learn that the input was corrupt.

Escaping user input with preg_quote

If part of a pattern comes from a variable, such as a search term, its special characters (., *, (, ? โ€ฆ) would be read as regex syntax. preg_quote($text, $delimiter) escapes them. Always pass your delimiter as the second argument so that it gets escaped too.

PHP Highlighting a search term safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last two calls show what goes wrong without escaping. Unescaped, C++ (2023) is still a valid pattern, but it means "one or more C characters (possessively), then a space, then a group containing 2023", so the literal text isn't found and you get 0. The unbalanced [ in price [USD doesn't compile at all, so preg_match() returns false and emits a warning (the @ hides it just for this demo). Either way, a user could break or change your pattern just by typing punctuation.

After any preg_ call, preg_last_error() and preg_last_error_msg() tell you whether the engine ran into trouble, as the next section shows.

Catastrophic backtracking (ReDoS)

When a match fails, the engine backtracks and tries other ways to divide the text between quantifiers. Nested quantifiers like (a+)+ can create an exponential number of ways, so a short input can keep the CPU busy for a very long time. Attackers exploit this with inputs crafted to fail slowly: a regular expression denial of service (ReDoS).

PHP protects itself with limits (pcre.backtrack_limit, one million by default). When a match hits the limit, the function returns false, not 0:

PHP A pattern that backtracks too much

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first match gives up and reports "Backtrack limit exhausted"; the rewritten pattern answers instantly. Two lessons follow:

  • Compare with === 1, never just truthiness, and treat false as an error. A check like if (!preg_match(...)) would treat a failed match the same as "no match", which may let bad input through or reject good input.
  • Avoid nested quantifiers over the same characters ((a+)+, (\w*)*, (.*,)*) and overlapping alternatives ((a|a)*). Keep patterns anchored and specific, and limit input length before matching.

Common patterns

Patterns you'll see again and again (keep them anchored when validating):

PHP
'/^\d+$/'                         // only digits
'/^-?\d+(\.\d+)?$/'               // a decimal number
'/^[a-z0-9]+(?:-[a-z0-9]+)*$/'    // a URL slug: words separated by single dashes
'/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i' // a hex color
'/^\d{4}-\d{2}-\d{2}$/'           // date shape (check the date itself with checkdate)
'/\s+/'                           // runs of whitespace
'/^\p{Lu}/u'                      // starts with an uppercase letter in any script

Shape is not meaning: 2026-02-31 matches the date pattern but isn't a real date. Validate the shape with a regex, then the value with real logic, like checkdate() or DateTimeImmutable (Dates and Times).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does preg_match('/\d{3}/', 'abc12345') return?

    preg_match returns 1 when it finds a match (here "123") and 0 when it doesn't. The matched text goes into the optional third argument.
  2. 2. What does preg_replace('/(\w+)@(\w+)/', '$2 at $1', 'ana@home') return?

    $1 is the first captured group ("ana") and $2 the second ("home"), so the replacement swaps them.
  3. 3. Why should a pattern built from user input go through preg_quote()?

    preg_quote escapes every regex metacharacter (and the delimiter you pass), so the input is matched literally.
  4. 4. A preg_match call hits the backtrack limit. What does it return?

    On an engine error, preg_ functions return false and preg_last_error_msg() explains why. That's why you should compare with === 1.
  5. 5. Which modifier lets . match a newline?

    s (dotall) makes the dot match newlines. m changes ^ and $ to work per line, x allows comments and u enables UTF-8.

Summary

  • PHP regexes are PCRE patterns in a string with delimiters and modifiers, like '/^\d+$/i'; write them in single quotes.
  • preg_match() finds the first match and returns 1, 0 or false; captures land in $matches.
  • preg_match_all() finds every match; PREG_SET_ORDER gives one array per match.
  • Named groups (?<name>โ€ฆ) make captures readable; PREG_UNMATCHED_AS_NULL keeps the array shape stable.
  • preg_replace() uses $1/${1} references; preg_replace_callback() computes each replacement.
  • preg_split() splits on a pattern; preg_grep() filters an array.
  • Key modifiers: i, m, s, u (always for UTF-8 text), x, D.
  • Escape variable parts with preg_quote($text, '/'), anchor validation patterns, avoid nested quantifiers and treat false as an error.

Next: Arrays, the data structure you'll use in almost every PHP program.