PHP Regex

Beginner
10 min read
Updated: Nov 2026
3 examples
PCRE & preg_*

Definition and Usage

PHP Regex means matching and changing text with PCRE (Perl Compatible Regular Expressions) through the preg_* functions. A pattern sits between delimiters (usually /.../), with optional modifiers after the closing delimiter (for example /hello/i for case-insensitive).

Test for a single match with preg_match(). Collect every match with preg_match_all(). Substitute with preg_replace(), or compute each replacement in a callback with preg_replace_callback() / preg_replace_callback_array().

Escape user text before you drop it into a pattern with preg_quote(). Split strings with preg_split(), keep matching array items with preg_grep(), and check failures with preg_last_error() / preg_last_error_msg().

This page explains the ideas. The Regex Functions index lists all 11 function guides.

Why PCRE exists in PHP.

String helpers such as strpos() find fixed text. Regular expressions describe patterns—digits, emails-shaped tokens, repeated words—so one call can validate, extract, or rewrite many forms of input.

Delimiters are required.

Unlike some languages, PHP patterns are not bare strings of regex syntax alone. Always wrap the pattern: /^\d+$/, not ^\d+$. Choose a delimiter that does not collide with characters inside the pattern, or escape those characters.

PHP Syntax

The usual pattern: write a delimited PCRE expression, then match, collect, replace, or quote:

PHP
// Delimiters + modifier (i = case-insensitive)
$ok = preg_match('/hello/i', 'Hello PHP');   // 1

// Capturing groups fill $matches
preg_match('/(\d{4})-(\d{2})-(\d{2})/', '2026-11-06', $m);
// $m[0] full match; $m[1], $m[2], $m[3] = year, month, day

// Every match
preg_match_all('/\b\w{4}\b/', 'this that word list', $all);

// Simple replace and quoted literal
$out = preg_replace('/\s+/', ' ', "a   b\tc");  // "a b c"
$lit = preg_quote('price $5.00', '/');          // price \$5\.00

// Callback when each replacement needs PHP logic
$up = preg_replace_callback('/\b\w+\b/', function ($m) {
  return strtoupper($m[0]);
}, 'hi php');                                   // HI PHP

Core Ideas

What to remember when you work with PHP PCRE:

IdeaFunctionRemember
First matchpreg_match()Returns 1 (match), 0 (no match), or false on error; optional $matches holds the first hit and groups
All matchespreg_match_all()Fills an array with every match; choose order with PREG_PATTERN_ORDER or PREG_SET_ORDER
Replacepreg_replace()Pattern, replacement, subject; use $1 / ${1} for backreferences
Filter subjectspreg_filter()Like replace, but returns only subjects that matched (handy for arrays)
Callback replacepreg_replace_callback()Run PHP for each match when a fixed replacement string is not enough
Many callbackspreg_replace_callback_array()Map several patterns to their own callbacks in one pass
Splitpreg_split()Break a string on a pattern (whitespace, commas, and more)
Grep an arraypreg_grep()Return array elements that match (or do not match) a pattern
Escape literalspreg_quote()Escape metacharacters before inserting a variable into a pattern
Errorspreg_last_error() / preg_last_error_msg()Inspect the last PCRE error code and message after a failed call

Delimiters, modifiers, and callbacks

Common modifiers after the closing delimiter include i (ignore case), m (^/$ per line), s (dot matches newlines), and u (UTF-8). Prefer preg_replace() for fixed text and backreferences. Reach for preg_replace_callback() when each hit needs a function—formatting, lookups, or strtoupper() on a capture. After a false return, call preg_last_error_msg() to see what went wrong.

Function Groups at a Glance

The Regex section is one family with four jobs. Use this map to pick the right group before you open a function page:

GroupTypical jobStart here
MatchTest for a match or collect every occurrence and capture groupspreg_match(), preg_match_all()
Replace & filterSubstitute text, keep only matched subjects, or replace via callbackspreg_replace(), preg_filter()
Split & grepBreak a string on a pattern, or filter an array of stringspreg_split(), preg_grep()
Quote & errorsEscape literals for safe patterns; read the last PCRE errorpreg_quote(), preg_last_error()

Neighboring tutorials that often sit next to this work: Strings for fixed-text search and replace, Filter for validating emails and integers without a custom pattern, Arrays when you walk preg_match_all() results, and Variables for storing matches and replacements.

PHP Examples

Three short, offline-safe scripts: preg_match() with delimiters and groups, preg_match_all() for every hit, and preg_replace() plus preg_quote(). Each block includes a fixed View Output panel.

Example 1 — preg_match() with delimiters and groups

Use a delimited pattern with the i modifier, then capture year, month, and day from a date string.

PHP
<?php
$greeting = 'Hello PHP';
$found = preg_match('/hello/i', $greeting);
echo 'case-insensitive hello: ', $found === 1 ? 'yes' : 'no', PHP_EOL;

$date = '2026-11-06';
$n = preg_match('/(\d{4})-(\d{2})-(\d{2})/', $date, $m);
echo 'date matched: ', $n === 1 ? 'yes' : 'no', PHP_EOL;
echo 'full: ', $m[0], PHP_EOL;
echo 'year: ', $m[1], PHP_EOL;
echo 'month: ', $m[2], PHP_EOL;
echo 'day: ', $m[3], PHP_EOL;
?>

How It Works

  1. /hello/i is a PCRE pattern: delimiters / wrap the text; i ignores case.
  2. preg_match() returns 1 when it finds a match, 0 when it does not.
  3. Parentheses (...) create capturing groups filled into $m[1], $m[2], and so on.
  4. $m[0] is always the full substring that matched the whole pattern.
  5. This is the beginner path: delimiters first, then one match with groups.

Example 2 — preg_match_all() for every word

Find every four-letter word and print how many matches and each full match.

PHP
<?php
$text = 'this that word list code fun';
$count = preg_match_all('/\b\w{4}\b/', $text, $matches);
echo 'count: ', $count, PHP_EOL;
echo 'matches: ', implode(', ', $matches[0]), PHP_EOL;
?>

How It Works

  1. \b is a word boundary; \w{4} means exactly four word characters.
  2. preg_match_all() returns the number of matches (here 4).
  3. By default, $matches[0] is an array of every full match.
  4. Use this when you need all hits, not only the first.
  5. For per-match groups as rows, pass PREG_SET_ORDER as the flags argument.

Example 3 — preg_replace() and preg_quote()

Collapse whitespace with a replace, then safely search for a literal price string that contains $ and ..

PHP
<?php
$messy = "a   b\tc";
$clean = preg_replace('/\s+/', ' ', $messy);
echo 'collapsed: ', $clean, PHP_EOL;

$needle = 'price $5.00';
$pattern = '/' . preg_quote($needle, '/') . '/';
$hay = 'Total price $5.00 today';
$hit = preg_match($pattern, $hay);
echo 'literal price found: ', $hit === 1 ? 'yes' : 'no', PHP_EOL;
echo 'pattern: ', $pattern, PHP_EOL;

// Callback when a fixed replacement is not enough
$up = preg_replace_callback('/\b\w+\b/', function ($m) {
  return strtoupper($m[0]);
}, 'hi php');
echo 'callback: ', $up, PHP_EOL;
?>

How It Works

  1. preg_replace('/\s+/', ' ', ...) turns runs of whitespace into a single space.
  2. preg_quote() escapes $ and . so they match literally inside the pattern.
  3. Pass the same delimiter (/) as the second argument so that character is escaped too if it appears.
  4. preg_replace_callback() runs PHP for each word—use it when the replacement is not a fixed string.
  5. Prefer plain preg_replace() for simple swaps; use callbacks only when you need custom logic.

Next: PHP Regex Functions Index

After you know delimiters, preg_match(), preg_match_all(), preg_replace(), preg_quote(), and when callbacks help, open the functions index for all 11 guides.

Start withWhy
preg_filter()First sidebar guide; replace and keep only matched subjects
preg_match()First-match test and capturing groups
preg_match_all()Collect every match into an array
preg_replace()Everyday pattern substitution
preg_quote()Escape variables before building a pattern
preg_replace_callback()Compute each replacement in PHP
preg_split()Split a string on a pattern

Full list: PHP Regex Functions index (/php/regex/function).

Frequently Asked Questions

PHP uses PCRE (Perl Compatible Regular Expressions) through the preg_* functions. You write a pattern between delimiters (for example /.../), then match, replace, split, or filter strings with helpers such as preg_match(), preg_match_all(), and preg_replace().
Every PCRE pattern in PHP must start and end with the same delimiter character, usually a forward slash: /pattern/. You can use other characters (# or ~) when the pattern itself contains many slashes. Optional modifiers such as i (case-insensitive) go after the closing delimiter: /hello/i.
preg_match() looks for the first match and returns 1, 0, or false. preg_match_all() finds every match and fills an array with all of them. Use preg_match() for a yes/no check or the first capture; use preg_match_all() when you need every occurrence.
Call preg_quote() when a piece of the pattern comes from user input or a variable that may contain regex metacharacters (. * + ? [ ] and so on). It escapes those characters so they match literally instead of changing the pattern meaning.
Use preg_replace_callback() or preg_replace_callback_array() when each replacement must be computed in PHP—for example uppercasing a capture, looking up a map, or formatting numbers. Use plain preg_replace() when the replacement is a fixed string or simple backreferences like $1.
Start with preg_match() and a simple delimited pattern. Then learn preg_match_all() for multiple matches, preg_replace() for substitutions, and preg_quote() before you build patterns from variables. Open the functions index for all 11 guides.

Browse every Regex function

Open the functions index for categorized guides with examples and FAQs.

Regex Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful