PCRE Reference
PCRE — Perl-Compatible Regex — reference. All functions start with preg_. Patterns are strings between matched delimiters (usually /).
Functions
| Function | Returns |
|---|---|
preg_match($p, $s, &$m, $f, $o) | 0/1/false. Sets $m on match. |
preg_match_all($p, $s, &$m, $f, $o) | Number of matches. |
preg_replace($p, $repl, $s) | New string. |
preg_replace_callback($p, $fn, $s) | Replace each match via a function. |
preg_split($p, $s, $limit = -1, $f = 0) | Array of pieces. |
preg_grep($p, $arr) | Filter array by pattern. |
preg_quote($s, $delim = null) | Escape regex metachars in a literal. |
Pattern atoms
| Atom | Matches |
|---|---|
. | Any char except newline. |
\d \D | Digit / non-digit. |
\w \W | Word (alnum + _) / non-word. |
\s \S | Whitespace / non-whitespace. |
\b \B | Word boundary / non-boundary. |
^ $ | Start / end (multiline mode: line). |
[abc] [^abc] [a-z] | Class / negation / range. |
Quantifiers
| Quantifier | Means |
|---|---|
* | 0 or more (greedy). |
+ | 1 or more. |
? | 0 or 1. |
{n} / {n,m} | Exact / range. |
Add ? for lazy / non-greedy | *? +? … |
Groups
| Form | Means |
|---|---|
(abc) | Capturing group. |
(?:abc) | Non-capturing. |
(?P<name>abc) | Named capture. |
(?=abc) / (?!abc) | Lookahead / negative lookahead. |
(?<=abc) / (?<!abc) | Lookbehind / negative. |
Modifier flags
| Flag | Effect |
|---|---|
i | Case-insensitive. |
m | Multiline — ^$ match line ends. |
s | Dotall — . matches \n. |
u | Unicode (UTF-8) mode. |
x | Extended — whitespace + # comments inside pattern. |
A | Anchor at start of subject. |
U | Invert greediness. |
Tip: Pattern strings using single quotes mean no need to double-escape backslashes:
'/\d+/' beats "/\\d+/".Example
Example
<?php
// PCRE — preg_* functions:
preg_match('/(\d+)/', 'order 4242', $m);
print_r($m);
echo preg_replace('/\s+/', '-', 'hello world');
print_r(preg_split('/,\s*/', 'a, b, c'));
Try it Yourself »
Exercise
Case-insensitive modifier flag.
/pattern/
A single letter.
Discussion
Loading…