PHP Regular Expressions
Reference for PHP regular expressions: PCRE syntax and the preg_ functions (preg_match, preg_replace, preg_split) with runnable examples for each.
A regular expression (regex) is a pattern that describes a set of strings. In PHP, regular expressions let you search text, validate input, extract data, and transform strings with far less code than manual character-by-character logic. This chapter covers the syntax, the preg_ functions, and the most useful advanced techniques, with runnable examples for each.
What are Regular Expressions
A regular expression is a sequence of characters that defines a search pattern. Instead of matching one fixed string, a pattern can describe a whole family of strings — "any digit", "one or more letters", "an email-shaped string", and so on. This makes regex ideal for:
- Validating user input (emails, phone numbers, postcodes).
- Searching for substrings that follow a shape rather than an exact value.
- Extracting data — pulling order numbers, dates, or URLs out of free text.
- Replacing and splitting text based on a pattern.
PHP uses PCRE (Perl-Compatible Regular Expressions), so the pattern syntax is the same as in Perl, JavaScript, and most other modern languages.
How Regular Expressions Work in PHP
In PHP, regular expressions are handled by the preg_ family of functions. Each takes a pattern as its first argument and performs a different operation.
Common preg_ functions
| Function | Description |
|---|---|
preg_match() | Searches for the first match. Returns 1 on match, 0 on no match, false on error |
preg_match_all() | Finds all matches. Returns the number of full matches found |
preg_replace() | Replaces every match with a replacement string |
preg_split() | Splits a string into an array using the pattern as the delimiter |
preg_quote() | Escapes characters that have special meaning in a pattern |
A common gotcha: preg_match() returns 0 (falsy) for no match and false for an error (such as a malformed pattern). Use the === operator when you need to tell those two cases apart.
The Basics of PHP Regular Expressions
A PHP pattern is a string with the pattern body wrapped in delimiters (commonly /), optionally followed by modifiers:
PHP regular expression syntax
/pattern/modifiersWhere pattern is the sequence of characters to match, and modifiers are optional letters that alter how the pattern behaves. The most commonly used modifiers in PHP are:
i: Case-insensitive matching (/php/imatchesPHP,Php,php).m: Multiline mode —^and$match at the start/end of each line, not just the whole string.s: "Dotall" mode —.also matches newline characters.u: Treat the pattern and subject as UTF-8. Use this whenever the text may contain non-ASCII characters.
Common pattern building blocks
Inside the pattern itself, a handful of metacharacters do most of the work:
| Token | Meaning |
|---|---|
\d \w \s | A digit, a word character, a whitespace character |
. | Any single character (except newline, unless s is set) |
+ * ? | One-or-more, zero-or-more, zero-or-one of the preceding token |
{2,4} | Between 2 and 4 repetitions |
^ $ | Start and end of the string (or line in m mode) |
[abc] | A character class — any one of a, b, or c |
(...) | A capturing group |
| | Alternation — match the pattern on either side |
PHP regular expression to replace text
Using PHP Regular Expressions to Validate User Input
One of the most common uses of regular expressions in PHP is to validate user input. For example, you can use a regular expression to ensure that a user-entered email address is in the correct format. The following code demonstrates how this can be done:
PHP regular expression to ensure that a user-entered email address is in the correct format
Note: While this regex works for basic validation, PHP provides the built-in filter_var($email, FILTER_VALIDATE_EMAIL) function for more robust, RFC-compliant email validation. For full form workflows, see PHP Form Validation.
Finding All Matches
While preg_match() stops at the first match, preg_match_all() collects every match into an array. This is the tool for extracting repeated data, such as every word, number, or tag in a string.
Extract every number from a string
<?php
$text = "Room 12, floor 3, building 7";
$count = preg_match_all("/\d+/", $text, $matches);
echo $count; // Outputs: 3
print_r($matches[0]); // Outputs: Array ( [0] => 12 [1] => 3 [2] => 7 )
?>Splitting Strings
preg_split() breaks a string into an array using a pattern as the delimiter. Unlike explode(), the delimiter can vary — here we split on any run of commas and whitespace:
<?php
$csv = "apple, banana, cherry";
$fruits = preg_split("/[\s,]+/", $csv);
print_r($fruits);
// Outputs: Array ( [0] => apple [1] => banana [2] => cherry )
?>Advanced Techniques for PHP Regular Expressions
Once the basics are comfortable, these techniques let you write expressive, precise patterns.
Capturing groups
Parentheses (...) capture part of a match so you can read it back from the $matches array. Index 0 holds the whole match; index 1 and up hold each group.
Named groups
(?<name>...) gives a group a readable label, so you can pull values out by name instead of a numeric index — much clearer for dates, prices, and other structured data.
<?php
$date = "2023-10-01";
preg_match("/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/", $date, $m);
echo $m["year"]; // Outputs: 2023
echo $m["month"]; // Outputs: 10
?>Alternation
The | operator matches one pattern or another. The example below matches whichever animal appears first:
<?php
preg_match("/cat|dog|bird/", "I love cats", $m);
echo $m[0]; // Outputs: cat
?>Other building blocks
- Non-capturing groups —
(?:...)group tokens together (for example, to apply a quantifier) without storing the match, which keeps the$matchesarray clean. - Lookahead / lookbehind —
(?=...),(?!...),(?<=...),(?<!...)match based on what comes before or after a position without consuming it. - Quantifiers —
{n},{n,}, and{n,m}match an exact count or a range of repetitions, e.g.\d{4}for exactly four digits.
When you need to match user-supplied text literally inside a pattern, run it through preg_quote() first so characters like . or * are escaped rather than treated as metacharacters.
Related Topics
- PHP RegEx (full guide) — a deeper walkthrough of PCRE syntax in PHP.
- PHP Strings — the non-regex string functions regex complements.
- PHP Form Validation — applying patterns to real form input.
Conclusion
PHP regular expressions are a powerful tool that can help you achieve a wide range of tasks. Whether you're validating user input, searching through text, or performing complex string manipulations, regular expressions are an essential part of the PHP developer's toolkit.