PHP Regex Cheat Sheet
PHP Regex Cheat Sheet
Functions
preg_match(pattern, subject[, submatches])
preg_match_all(pattern, subject[, submatches])
preg_replace(pattern, replacement, subject)
preg_replace_callback(pattern, callback, subject)
preg_grep(pattern, array)
preg_split(pattern, subject)
Base Character Classes
\w Any word character (a!" #!$ _)
\% Any non word character
\s %hitespace (space, tab &'())
\* Any non whitepsace character
\d +igits (#!$)
\+ Any non digit character
, (-eriod) . Any character e/cept newline
Meta Characters
0 *tart o1 subject (or line in multiline mode)
2 3nd o1 subject (or line in multiline mode)
[ *tart character class de1inition
] 3nd character class de1inition
4 Alternates, eg (a4b) matches a or b
( *tart subpattern
) 3nd subpattern
\ 3scape character
Quantifiers
n5 6ero or more o1 n
n7 8ne or more o1 n
n9 6ero or one occurrences o1 n
:n; n occurrences e/actly
:n,; At least n occurrences
:,m; At most m occurrences
:n,m; <etween n and m occurrences (inclusi=e)
Pattern Modifiers
i &aseless . ignore case
m >ultiline mode ! 0 and 2 match start and
end o1 lines
s +otall ! , class includes newline
/ 3/tended. comments ? whitespace
e preg_replace only . enables e=aluation o1
replacement as -@- code
* 3/tra analysis o1 pattern
A -attern is ungreedy
u -attern is treated as AB)!C
Point based assertions
\b %ord boundary
\< Dot a word boundary
\A *tart o1 subject
\6 3nd o1 subject or newline at end
\" 3nd o1 subject
\E )irst matching position in subject
Subpattern Modifiers & Assertions
(9F) Don capturing subpattern ((9F1oo41u)bar) matches 1oobar or 1ubar without 1oo or 1u
appearing as a captured subpattern
(9G) -ositi=e look ahead assertion 1oo(9Gbar) matches 1oo when 1ollowed by bar
(9H) Degati=e look ahead assertion 1oo(9Hbar) matches 1oo when not 1ollowed by bar
(9IG) -ositi=e look behind assertion (9IG1oo)bar matches bar when preceded by 1oo
(9IH) Degati=e look behind assertion (9IH1oo)bar matches bar when not preceded by 1oo
(9J) 8nce!only subpatterns (9J\d7)bar -er1ormance enhancing when bar not present
(9(/)) &onditional subpatterns (9(K)1oo41u)bar >atches 1oo i1 K
rd
subpattern has matched, 1u i1 not
(9L) &omment (9L -attern does / y or ")