PHP supports regular expressions through the PCRE library and the preg_ functions. The php regex preg_match function tests a string against a pattern and returns 1 for a match, 0 for no match and false on error, while preg_match_all() finds every match and preg_replace() rewrites text. Patterns are written as strings with a delimiter at each end, such as '/\d+/', and flags after the closing delimiter.
This guide covers pattern syntax, capture groups, named groups, replacing and splitting, and the pitfalls around errors and security. Examples target PHP 8.3 or newer.
A PHP pattern is a string whose first character is the delimiter. Slash is most common, but #, ~ and % are useful when the pattern itself contains many slashes. Flags follow the closing delimiter.
| Element | Meaning |
|---|---|
. | any character except newline |
\d, \w, \s | digit, word character, whitespace |
^, $ | start and end of the subject |
*, +, ? | zero or more, one or more, optional |
{2,4} | between two and four repeats |
[a-z], [^0-9] | character class, negated class |
(...) | capture group |
(?:...) | non-capturing group |
a|b | alternation |
Common flags are i (ignore case), m (multi-line anchors), s (dot matches newline), x (allow whitespace and comments) and u (treat the subject as UTF-8).
preg_match($pattern, $subject, &$matches) stops at the first match and fills $matches, where index 0 is the whole match and the following indexes are the groups.
Always compare the return value correctly. A result of false means an error, such as a malformed pattern, and is different from 0. Check the details with preg_last_error_msg().
Named groups make results self-explanatory. Use (?<name>...) and read $m['name'].
Do not try to validate email addresses fully with a regular expression. For real forms use filter_var($email, FILTER_VALIDATE_EMAIL) and confirm ownership by sending a message.
preg_match_all() returns the number of matches. By default $matches is grouped by pattern index; pass PREG_SET_ORDER to get one entry per match.
preg_replace() swaps matches using $1 or ${1} for groups, and preg_replace_callback() lets a function compute the replacement. preg_split() splits on a pattern.
The output of preg_split() here is ['x', 'y', 'z', 'w']. The old e modifier was removed in PHP 7.0, and preg_replace_callback() is its replacement.
Quantifiers are greedy by default and take as much text as possible. Add ? to make them lazy.
Use ^ and $ (or \A and \z) to require that the whole string matches. Without anchors, /\d+/ also matches inside abc123def. Note that $ also matches before a final newline; use \z or the D flag when that matters.
preg_quote($input, '/'), passing the delimiter as the second argument.u flag for UTF-8 text so . and \p{L} work on characters.(a+)+ can cause catastrophic backtracking. PCRE stops at the pcre.backtrack_limit setting and the function returns false, so always check for it.str_contains() and str_replace() are simpler and faster than a regex for fixed text.DOMDocument or the Dom\HTMLDocument class available since PHP 8.4.It returns 1 if the pattern matched, 0 if it did not, and false if an error occurred. Use === 1 or a plain truthy check when errors are not a concern.
preg_match() stops at the first match, while preg_match_all() collects all of them and returns the count.
The PCRE functions use the first character as the delimiter so that flags can be written after the closing one. Choose a delimiter that does not appear in the pattern.
No. The ereg family was removed in PHP 7.0. Use the preg_ functions, and use mb_ereg only for legacy multibyte encodings.
The preg_ functions give PHP the full PCRE regular expression engine. Use preg_match() for one match, preg_match_all() for all matches, preg_replace() and preg_replace_callback() to rewrite text, and preg_split() to split. Prefer named groups, anchor patterns that must match the whole string, add u for UTF-8, escape input with preg_quote(), and check for errors with preg_last_error_msg().