iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PCRE Reference

PCRE — Perl-Compatible Regex — reference. All functions start with preg_. Patterns are strings between matched delimiters (usually /).

Functions

FunctionReturns
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

AtomMatches
.Any char except newline.
\d \DDigit / non-digit.
\w \WWord (alnum + _) / non-word.
\s \SWhitespace / non-whitespace.
\b \BWord boundary / non-boundary.
^ $Start / end (multiline mode: line).
[abc] [^abc] [a-z]Class / negation / range.

Quantifiers

QuantifierMeans
*0 or more (greedy).
+1 or more.
?0 or 1.
{n} / {n,m}Exact / range.
Add ? for lazy / non-greedy*? +?

Groups

FormMeans
(abc)Capturing group.
(?:abc)Non-capturing.
(?P<name>abc)Named capture.
(?=abc) / (?!abc)Lookahead / negative lookahead.
(?<=abc) / (?<!abc)Lookbehind / negative.

Modifier flags

FlagEffect
iCase-insensitive.
mMultiline — ^$ match line ends.
sDotall — . matches \n.
uUnicode (UTF-8) mode.
xExtended — whitespace + # comments inside pattern.
AAnchor at start of subject.
UInvert 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/

Test yourself

Q1. Function prefix is…
Q2. \b means…
Q3. Modifier for case-insensitive is…

Discussion

Loading…