PHP Regex Cheat Sheet
Every symbol of a PHP pattern on one line, with what it does and a line of code that shows it: the comment at the end of a statement is what the statement prints. The functions come after the syntax, then the messages PHP prints for a pattern it refuses.
How to read the code:
echo preg_match(…)prints1when the pattern matches and0when it does not.- A call followed by
? $m[0] : 'none'prints the text the pattern matched, ornone. - Two calls on one line print their results in that order, separated by a space. An array is printed by
json_encode().
Delimiters and modifiers
A pattern is an expression between two delimiters, and its modifiers follow the closing one. In /^[a-z]+$/i, the expression is ^[a-z]+$ and the modifier is i.
Delimiters
/…/— the delimiter most PHP code uses. Any character that is not a letter, a digit, a backslash, a space or a NUL byte can be one.#…#,~…~and%…%spare the slashes of a path or a URL.(…),[…],{…},<…>— paired delimiters. The pattern ends at the closing half that balances the opening one, so the same pair can nest inside:{\d{2}}.\/— the delimiter inside the pattern, escaped. Another delimiter removes the escape.
echo preg_match('/^[a-z]+$/i', 'Abc'), PHP_EOL; // 1
echo preg_match('#https?://#', 'https://example.com'), PHP_EOL; // 1
echo preg_match('~[0-9]+~', 'a42'), ' ', preg_match('%[0-9]+%', 'a42'), PHP_EOL; // 1 1
echo preg_match('{\d{2}}', 'a42'), ' ', preg_match('(\(\d+\))', '(42)'), PHP_EOL; // 1 1
echo preg_match('[\d+]', 'a42'), ' ', preg_match('<\d+>', 'a42'), PHP_EOL; // 1 1
echo preg_match('/^\/users\/\d+$/', '/users/42'), ' ', preg_match('#^/users/\d+$#', '/users/42'), PHP_EOL; // 1 1
Modifiers
The letters after the closing delimiter, one line each:
i— a letter of the pattern matches its upper and its lower case.m—^and$match at the start and at the end of every line, not only of the subject.s—.also matches a newline.x— the spaces and the line breaks of the pattern are ignored, and#starts a comment: a long pattern can be written over several lines.u— the pattern and the subject are read as UTF-8.\p{…}needs it,.matches one character and not one byte,\wand\dmatch the letters and the digits of every script, and\band\sfollow.U— the greediness of every quantifier is inverted: lazy by default, and greedy after a?.D—$matches at the very end of the subject, not before a final newline.mmakes it ignored.A— the pattern can match only where the search starts.J— two groups may have the same name.n— a plain(…)group captures nothing; only a named group(?<name>…)does, and\1to a plain group is refused. From PHP 8.2.r— withiandu, case is no longer ignored between a letter of ASCII and a character outside ASCII: the Kelvin sign U+212A stops matchingk. From PHP 8.4.S,X— accepted, and without effect:Ssince PHP 7.3,Xsince PHP 8.0.e— removed in PHP 7.0. PHP 8.4 answersUnknown modifier 'e'; the releases before,The /e modifier is no longer supported, use preg_replace_callback instead.
echo preg_match('/cat/', 'CAT'), ' ', preg_match('/cat/i', 'CAT'), PHP_EOL; // 0 1
echo preg_match('/^b$/', "a\nb"), ' ', preg_match('/^b$/m', "a\nb"), PHP_EOL; // 0 1
echo preg_match('/a.b/', "a\nb"), ' ', preg_match('/a.b/s', "a\nb"), PHP_EOL; // 0 1
echo preg_match("/a b # two letters\n/x", 'ab'), PHP_EOL; // 1
echo preg_match('/^\w+$/u', 'café'), ' ', preg_match('/^\w+$/', 'café'), PHP_EOL; // 1 0
echo preg_match('/<.+>/U', '<b>hi</b>', $m) ? $m[0] : 'none', PHP_EOL; // <b>
echo preg_match('/<.+?>/U', '<b>hi</b>', $m) ? $m[0] : 'none', PHP_EOL; // <b>hi</b>
echo preg_match('/^cat$/D', "cat\n"), ' ', preg_match('/^cat$/mD', "cat\n"), PHP_EOL; // 0 1
echo preg_match('/b/A', 'ab', $m, 0, 1), ' ', preg_match('/b/A', 'ab', $m, 0, 0), PHP_EOL; // 1 0
preg_match('/(?<n>a)|(?<n>b)/J', 'b', $m);
echo $m['n'], PHP_EOL; // b
preg_match('/(a)(b)/n', 'ab', $m);
echo json_encode($m), PHP_EOL; // ["ab"]
preg_match('/(?<w>\w+)\d/n', 'a1', $m);
echo $m['w'], PHP_EOL; // a
echo preg_match('/k/iu', "\u{212A}"), ' ', preg_match('/k/iur', "\u{212A}"), PHP_EOL; // 1 0
echo preg_match('/a/SX', 'a'), PHP_EOL; // 1
Inside a pattern, (?i) turns a modifier on from where it stands and (?-i) turns it off. (?i:…) applies it to one group only. The letters u, A and D have no inline form: (?u) is refused.
echo preg_match('/a(?i)b/', 'aB'), ' ', preg_match('/a(?i)b/', 'Ab'), PHP_EOL; // 1 0
echo preg_match('/(?i:a)b/', 'Ab'), ' ', preg_match('/(?i:a)b/', 'AB'), PHP_EOL; // 1 0
echo preg_match('/(?i)a(?-i)b/', 'Ab'), ' ', preg_match('/(?i)a(?-i)b/', 'AB'), PHP_EOL; // 1 0
Each modifier in depth: PHP regex modifiers.
Characters and character classes
.— any one character, except a newline. Withs, the newline too. Underu, one character of any script, never one byte of it.[abc]— one character from the list.[a-z]— a range: every character from the first to the second, by code point.[0-9],[A-Za-z0-9].[^abc]— one character that is not in the list.-— makes a range between two characters. First or last in the class, it is a hyphen.[.],[(],[$]— inside a class,.,(,),{,},*,+,?,|and$are plain characters.\still escapes,]closes the class unless it is escaped or comes first, and^negates only as the first character.
echo preg_match('/a.b/', "a\nb"), ' ', preg_match('/a.b/s', "a\nb"), PHP_EOL; // 0 1
echo preg_match_all('/./u', 'aé', $m), ' ', preg_match_all('/./', 'aé', $m), PHP_EOL; // 2 3
echo preg_match('/[aeiou]/', 'hello', $m) ? $m[0] : 'none', PHP_EOL; // e
echo preg_match('/^#[0-9a-f]{6}$/i', '#F0E0D0'), ' ', preg_match('/^[A-Za-z0-9_]+$/', 'v2_0'), PHP_EOL; // 1 1
echo preg_match('/[^0-9]+/', 'abc123', $m) ? $m[0] : 'none', PHP_EOL; // abc
echo preg_match('/^[a-z]+$/', 'a-z'), ' ', preg_match('/^[a-z-]+$/', 'a-z'), PHP_EOL; // 0 1
echo preg_match('/[$().*+?{}|]/', '2+2', $m) ? $m[0] : 'none', PHP_EOL; // +
echo preg_match('/[]]/', 'a]b'), ' ', preg_match('/[\]]/', 'a]b'), PHP_EOL; // 1 1
echo preg_match('/[a^b]/', 'x^y', $m) ? $m[0] : 'none', PHP_EOL; // ^
\d— one digit,[0-9].\D— one character that is not a digit.\w— one word character: a letter, a digit or_, as[a-zA-Z0-9_]. Underu, of every script.\W— the others.\s— one whitespace character: a space, a tab, a newline, a carriage return, a form feed or a vertical tab. Underu, the other spaces of Unicode too.\S— the others.\h— one horizontal whitespace character: a space or a tab, and underuevery space of Unicode.\v— one vertical whitespace character: a newline, a vertical tab, a form feed or a carriage return.[[:alpha:]],[[:digit:]],[[:alnum:]],[[:space:]]— POSIX classes. They stand inside a class;[:alpha:]alone is refused.\p{L}— a letter,\p{N}a digit of any script, underu.\P{L}— one character that is not a letter.|— or:cat|dogmatches one or the other. Without a group it reaches both ends of the pattern, so^cat|dog$means^catordog$.
echo preg_match('/\d+/', 'Order 42', $m) ? $m[0] : 'none', PHP_EOL; // 42
echo preg_match('/\D+/', '123abc', $m) ? $m[0] : 'none', PHP_EOL; // abc
echo preg_match('/^\d$/u', '٣'), ' ', preg_match('/^\d$/', '٣'), PHP_EOL; // 1 0
echo preg_match('/\w+/', 'hello_world!', $m) ? $m[0] : 'none', PHP_EOL; // hello_world
echo preg_match('/\W/', 'a!b', $m) ? $m[0] : 'none', PHP_EOL; // !
echo preg_match('/^\s$/', "\t"), ' ', preg_match('/^\s$/', 'x'), PHP_EOL; // 1 0
echo preg_match('/^\s$/u', "\u{A0}"), ' ', preg_match('/^\s$/', "\u{A0}"), PHP_EOL; // 1 0
echo preg_match('/\S+/', ' hi ', $m) ? $m[0] : 'none', PHP_EOL; // hi
echo preg_match('/^\h$/', "\t"), ' ', preg_match('/^\h$/', "\n"), ' ', preg_match('/^\h$/u', "\u{A0}"), PHP_EOL; // 1 0 1
echo preg_match('/^\v$/', "\n"), ' ', preg_match('/^\v$/', ' '), PHP_EOL; // 1 0
echo preg_match('/^[[:alpha:]]+$/', 'Hello'), ' ', preg_match('/^[[:digit:]]{4}$/', '2024'), PHP_EOL; // 1 1
echo preg_match('/^[[:alnum:]_]+$/', 'v2_0'), ' ', preg_match('/^[[:space:]]*$/', " \t"), PHP_EOL; // 1 1
echo preg_match('/^\p{L}+$/u', 'café'), ' ', preg_match('/^\p{L}+$/u', 'café!'), PHP_EOL; // 1 0
echo preg_match('/^\p{N}+$/u', '2024'), ' ', preg_match('/^\P{L}+$/u', '2024'), PHP_EOL; // 1 1
echo preg_match('/cat|dog/', 'hotdog', $m) ? $m[0] : 'none', PHP_EOL; // dog
echo preg_match('/^cat|dog$/', 'the dog'), ' ', preg_match('/^(cat|dog)$/', 'the dog'), PHP_EOL; // 1 0
In depth: Chapter 2: Character Classes & Escapes.
Anchors and boundaries
An anchor matches a position. It consumes no character.
^— the start of the subject. Withm, the start of every line.$— the end of the subject, and also the position just before a newline that ends the subject. Withm, the end of every line.\A— the start of the subject, whatever the modifiers.\z— the end of the subject, and nothing after it.\Z— the end of the subject, or just before a newline that ends it.\b— a word boundary: between a word character and a character that is not one, or at the start or the end of the subject.\B— a position that is not a word boundary.\G— the position where the search starts: the start of the subject, or the offset given to the function.
echo preg_match('/^cat/', 'cat food'), ' ', preg_match('/^cat/', 'the cat'), PHP_EOL; // 1 0
echo preg_match('/cat$/', 'the cat'), ' ', preg_match('/cat$/', 'cat food'), PHP_EOL; // 1 0
echo preg_match('/^cat$/', "cat\n"), ' ', preg_match('/^cat$/', "cat\ncat"), PHP_EOL; // 1 0
echo preg_match('/^cat$/m', "cat\ncat"), ' ', preg_match('/^cat$/D', "cat\n"), PHP_EOL; // 1 0
echo preg_match('/\Acat/m', "cat\ncat"), ' ', preg_match('/\Abird/m', "cat\nbird"), PHP_EOL; // 1 0
echo preg_match('/bird\z/m', "cat\nbird"), ' ', preg_match('/cat\z/', "cat\n"), PHP_EOL; // 1 0
echo preg_match('/cat\Z/', "cat\n"), ' ', preg_match('/cat\z/', "cat\n"), PHP_EOL; // 1 0
echo preg_match('/\bcat\b/', 'the cat'), ' ', preg_match('/\bcat\b/', 'category'), PHP_EOL; // 1 0
echo preg_match('/\bcaf\b/u', 'café'), ' ', preg_match('/\bcaf\b/', 'café'), PHP_EOL; // 0 1
echo preg_match('/\Bcat\B/', 'concatenate'), ' ', preg_match('/\Bcat\B/', 'the cat'), PHP_EOL; // 1 0
echo preg_match('/\Gcat/', 'the cat', $m, 0, 4), ' ', preg_match('/\Gcat/', 'the cat', $m, 0, 0), PHP_EOL; // 1 0
In depth: Chapter 3: Anchors & Boundaries.
Quantifiers
A quantifier says how many times the element right before it repeats: one character, one class or one group.
*— zero or more times.+— one or more times.?— zero or one time: optional.{n}— exactlyntimes.{n,}—ntimes or more.{n,m}— fromntomtimes.{,m}— from zero tomtimes. From PHP 8.4; before, it is the text{,m}.?after a quantifier — lazy: as few times as the rest of the pattern allows.*?,+?,??,{n,m}?.+after a quantifier — possessive: it never gives back what it took.*+,++,?+,{n,m}+.
echo preg_match('/ab*/', 'a', $m) ? $m[0] : 'none', PHP_EOL; // a
echo preg_match('/ab*/', 'abbb', $m) ? $m[0] : 'none', PHP_EOL; // abbb
echo preg_match('/ab+/', 'abbb', $m) ? $m[0] : 'none', PHP_EOL; // abbb
echo preg_match('/ab+/', 'a', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/colou?r/', 'colour', $m) ? $m[0] : 'none', PHP_EOL; // colour
echo preg_match('/^\d{4}$/', '2024'), ' ', preg_match('/^\d{4}$/', '202'), PHP_EOL; // 1 0
echo preg_match('/^\d{2,}$/', '123'), ' ', preg_match('/^\d{2,}$/', '1'), PHP_EOL; // 1 0
echo preg_match('/^\d{2,4}$/', '1234'), ' ', preg_match('/^\d{2,4}$/', '12345'), PHP_EOL; // 1 0
echo preg_match('/^a{,2}$/', 'aa'), ' ', preg_match('/^a{,2}$/', 'aaa'), PHP_EOL; // 1 0
echo preg_match('/<.+>/', '<b>hi</b>', $m) ? $m[0] : 'none', PHP_EOL; // <b>hi</b>
echo preg_match('/<.+?>/', '<b>hi</b>', $m) ? $m[0] : 'none', PHP_EOL; // <b>
echo preg_match('/a.*?b/', 'abab', $m) ? $m[0] : 'none', PHP_EOL; // ab
echo preg_match('/a{2,4}?/', 'aaaa', $m) ? $m[0] : 'none', PHP_EOL; // aa
echo preg_match('/a??/', 'a', $m) ? "[$m[0]]" : 'none', PHP_EOL; // []
echo preg_match('/a+a/', 'aa', $m) ? $m[0] : 'none', PHP_EOL; // aa
echo preg_match('/a++a/', 'aa', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/a*+a/', 'aa'), ' ', preg_match('/a?+a/', 'a'), ' ', preg_match('/a{1,3}+a/', 'aaa'), PHP_EOL; // 0 0 0
In depth: Chapter 4: Quantifiers & Greediness.
Groups, backreferences and recursion
(…)— a capturing group. What it matches goes to$m, by number:$m[0]is the whole match,$m[1]the first group.(?:…)— a group that captures nothing. It groups for a quantifier or for|.(?<name>…)— a group with a name:$m['name'].(?'name'…)and(?P<name>…)are the same group.\1,\2— a backreference: the text group 1, group 2 matched.\k<name>— the text of a named group.\g{1}takes a number,\g{name}a name.(?R)— recursion: the whole pattern, again, from where it stands.(?1)and(?&name)run one group again.(?(1)yes|no)— a conditional:yesif group 1 took part in the match, elseno.(?>…)— an atomic group: once it is closed, the engine never backtracks into it.
preg_match('/(\d{4})-(\d{2})-(\d{2})/', '2024-01-15', $m);
echo $m[1], ' ', $m[2], ' ', $m[3], PHP_EOL; // 2024 01 15
preg_match('/(?:\d{4})-(\d{2})/', '2024-01-15', $m);
echo json_encode($m), PHP_EOL; // ["2024-01","01"]
preg_match('/(?<year>\d{4})-(?<month>\d{2})/', '2024-01-15', $m);
echo "$m[year] / $m[month]", PHP_EOL; // 2024 / 01
preg_match("/(?'day'\d{2})\/(?P<month>\d{2})/", '15/01', $m);
echo $m['day'], ' ', $m['month'], PHP_EOL; // 15 01
echo preg_match('/(\w+) \1/', 'hello hello', $m) ? $m[0] : 'none', PHP_EOL; // hello hello
echo preg_match('/(?<w>\w+) \k<w>/', 'bye bye', $m) ? $m[0] : 'none', PHP_EOL; // bye bye
echo preg_match('/(?<w>\w+) \g{w}/', 'oy oy', $m) ? $m[0] : 'none', PHP_EOL; // oy oy
echo preg_match('/(\w+) \g{1}/', 'hi hi', $m) ? $m[0] : 'none', PHP_EOL; // hi hi
echo preg_match('/(\w)(\w)\2\1/', 'abba', $m) ? $m[0] : 'none', PHP_EOL; // abba
echo preg_match('/\((?:[^()]|(?R))*\)/', 'f(a(b)c)', $m) ? $m[0] : 'none', PHP_EOL; // (a(b)c)
echo preg_match('/(\d+)-(?1)/', '12-12', $m) ? $m[0] : 'none', PHP_EOL; // 12-12
echo preg_match('/(?<n>\d+)-(?&n)/', '34-34', $m) ? $m[0] : 'none', PHP_EOL; // 34-34
echo preg_match('/^(a)?(?(1)b|c)$/', 'ab'), ' ', preg_match('/^(a)?(?(1)b|c)$/', 'c'), PHP_EOL; // 1 1
echo preg_match('/^(a)?(?(1)b|c)$/', 'ac'), PHP_EOL; // 0
echo preg_match('/(?>a+)b/', 'aab'), ' ', preg_match('/(?>a+)a/', 'aa'), PHP_EOL; // 1 0
In depth: Chapter 5: Groups & Alternation and Chapter 7: Backreferences, Subroutines & Recursion.
Lookarounds
A lookaround checks the text before or after the position, and consumes nothing of it.
(?=…)— positive lookahead: what follows must match.(?!…)— negative lookahead: what follows must not match.(?<=…)— positive lookbehind: what precedes must match.(?<!…)— negative lookbehind: what precedes must not match.(?*…),(?<*…)— non-atomic lookaround: as(?=…)and(?<=…), but the engine may go back into it once it has matched. From PCRE2 10.35, which PHP 8.0 bundles.
The non-atomic lookahead differs from (?=…) when the rest of the pattern needs the captured text shorter. On aaab, (?=(a+)) captures aaa and keeps it, so \1ab has too little left. (?*(a+)) gives characters back until \1 is aa.
echo preg_match('/\d+(?= USD)/', '100 USD', $m) ? $m[0] : 'none', PHP_EOL; // 100
echo preg_match('/\bcat(?!\w)/', 'one cat', $m) ? $m[0] : 'none', PHP_EOL; // cat
echo preg_match('/\bcat(?!\w)/', 'two cats', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/(?<=\$)\d+/', 'Total: $49', $m) ? $m[0] : 'none', PHP_EOL; // 49
echo preg_match('/(?<!\$)\b\d+/', 'Total: 49', $m) ? $m[0] : 'none', PHP_EOL; // 49
echo preg_match('/(?<!\$)\b\d+/', 'Total: $49', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/^(?=.*\d).{8,}$/', 'abcdefg1', $m) ? $m[0] : 'none', PHP_EOL; // abcdefg1
echo preg_match('/(?=(a+))\1ab/', 'aaab', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/(?*(a+))\1ab/', 'aaab', $m) ? $m[0] : 'none', PHP_EOL; // aaab
echo preg_match('/(?<*\d{2})px/', '24px', $m) ? $m[0] : 'none', PHP_EOL; // px
A lookbehind needs a maximum length. Before PHP 8.4, each of its branches must have one fixed length: (?<=a|bb) is accepted and (?<=a{1,3}) is refused. From PHP 8.4, a branch may cover several lengths, as long as it has a maximum of 255 characters. (?<=a+), which has none, is refused on every PHP. The message by release, and the rewrites: lookbehind assertion is not fixed length.
echo preg_match('/(?<=a|bb)c/', 'bbc'), ' ', preg_match('/(?<=a{1,3})b/', 'aaab'); // 1 1
A non-atomic lookbehind of several lengths gives a wrong answer under the JIT of PCRE2 10.44, the release PHP 8.4 to 8.6 bundle: /(?<*(aaa|a)b)\1c/ finds nothing in aaabac with the default pcre.jit=1, and ac with pcre.jit=0. The change log of PCRE2 dates the correction to 10.48.
In depth: Chapter 6: Lookarounds & Assertions.
Escapes and special characters
\— makes the next character plain:\.is a dot,\*a star,\(and\)parentheses,\[and\]brackets,\{and\}braces, and\?,\+,\^,\$,\|and\\the same. In a PHP string between single quotes, one backslash is written\\.\n,\t,\r— a newline, a tab, a carriage return.\fa form feed,\ethe escape character,\0a NUL byte.\xHH— the character of a two-digit hexadecimal code:\x41isA.\x{…}takes more digits, and needsupast\x{FF}:\x{E9}isé.\Q…\E— every character between the two is plain, metacharacters included.preg_quote()— the same for a text known at run time only: see the functions.
echo preg_match('/file\.txt/', 'fileXtxt'), ' ', preg_match('/file.txt/', 'fileXtxt'), PHP_EOL; // 0 1
echo preg_match('/\[\]\{\}\*\+\?\^\|/', '[]{}*+?^|', $m) ? $m[0] : 'none', PHP_EOL; // []{}*+?^|
echo preg_match('/\(\d\)/', '(5)', $m) ? $m[0] : 'none', PHP_EOL; // (5)
echo preg_match("/a\nb/", "a\nb"), ' ', preg_match("/a\tb/", "a\tb"), ' ', preg_match("/a\r\nb/", "a\r\nb"), PHP_EOL; // 1 1 1
echo preg_match('/^\f$/', "\f"), ' ', preg_match('/^\e$/', "\e"), ' ', preg_match('/^\0$/', "\0"), PHP_EOL; // 1 1 1
echo preg_match('/\x41/', 'A'), ' ', preg_match('/^\x{E9}$/u', "\u{E9}"), PHP_EOL; // 1 1
echo preg_match('/\Qa+b\E/', 'a+b', $m) ? $m[0] : 'none', PHP_EOL; // a+b
echo preg_match('/\Qa+b\E/', 'aab', $m) ? $m[0] : 'none', PHP_EOL; // none
echo preg_match('/\\\\/', 'a\b', $m) ? $m[0] : 'none', PHP_EOL; // \
echo preg_quote('a+b (c)', '/'), PHP_EOL; // a\+b \(c\)
The preg functions
preg_match()—1if the pattern matches once,0if it does not. The third argument receives the match and its groups.preg_match_all()— the number of matches. The third argument receives them all.preg_replace()— the subject with every match replaced.$1in the replacement is the text of group 1.preg_replace_callback()— the same, with the replacement built by a function for each match.preg_split()— an array: the subject cut at every match.preg_grep()— the entries of an array that match, with their keys.preg_quote()— a text with its metacharacters escaped, ready to stand in a pattern.preg_last_error()— the error of the last call,PREG_NO_ERRORwhen all went well;preg_last_error_msg()says it in words. A call that fails returnsfalse: that is notno match
.
echo preg_match('/\d+/', 'abc123'), PHP_EOL; // 1
preg_match('/(\d+)-(\d+)/', 'code 12-34', $m);
echo json_encode($m), PHP_EOL; // ["12-34","12","34"]
echo preg_match_all('/\d+/', 'a1 b22 c333', $m), PHP_EOL; // 3
echo json_encode($m[0]), PHP_EOL; // ["1","22","333"]
echo preg_replace('/(\d+)-(\d+)/', '$2-$1', '12-34'), PHP_EOL; // 34-12
echo preg_replace_callback('/\d+/', fn ($m) => $m[0] * 2, 'a1b22'), PHP_EOL; // a2b44
echo json_encode(preg_split('/[\s,]+/', 'a, b,c')), PHP_EOL; // ["a","b","c"]
echo json_encode(preg_grep('/^\d+$/', ['a', '1', '2', 'b'])), PHP_EOL; // {"1":"1","2":"2"}
echo preg_quote('a.b/c', '/'), PHP_EOL; // a\.b\/c
var_dump(preg_match('/\p{L}/u', "\xC3\x28")); // bool(false)
echo preg_last_error_msg(), PHP_EOL; // Malformed UTF-8 characters, possibly incorrectly encoded
var_dump(preg_last_error() === PREG_NO_ERROR); // bool(false)
preg_replace() in depth: preg_replace in PHP.
The mistakes everyone meets once
The message PHP prints, and the page that says why and how to fix it:
Unknown modifier— a delimiter stands inside the patternNo ending delimiter found— the closing delimiter is missing or escapedDelimiter must not be alphanumeric, backslash, or NUL byte— the pattern has no delimitersEmpty regular expression— a variable held nothingmissing closing parenthesis— a(opens a group that no)closesunmatched closing parenthesis— a)closes no groupunrecognized character after (? or (?-—(?is followed by a letter PCRE2 does not read theremissing terminating ] for character class— a[opens a class that no]closesrange out of order in character class— a range runs backwards, as[z-a]quantifier does not follow a repeatable item— a quantifier follows an anchor or another quantifiernumbers out of order in {} quantifier— the maximum comes first, as{5,2}number too big in {} quantifier— a count past 65535unrecognized character follows \— a backslash precedes a letter PCRE2 knows no escape forPCRE2 does not support \F, \L, \l, \N{name}, \U, or \u— the\uXXXXof JavaScriptunknown property after \P or \p—\p{…}names no property PCRE2 knowsPOSIX named classes are supported only within a class—[:alpha:]was written outside a classsyntax error in subpattern name— a group name is not closed, or holds a character a name cannottwo named subpatterns have the same name— rename one, or allow it withJreference to non-existent subpattern— a backreference or a call names a group the pattern does not havelookbehind assertion is not fixed length— a lookbehind has no maximum lengthcharacter code point value in \x{} or \o{} is too large— a code point past10FFFF, or pastFFwithoutuparentheses are too deeply nested— 250 levels at mostregular expression is too large— the compiled pattern passes 64 KiBMalformed UTF-8 characters, possibly incorrectly encoded— underu, the subject is not valid UTF-8UTF-8 error: illegal byte (0xfe or 0xff)— underu, the pattern is not valid UTF-8Backtrack limit exhausted— the pattern backtracked past its limitJIT stack limit exhausted— a recursion with no way outJIT compilation failed— the JIT refused the pattern, and PHP matches without itAllocation of JIT memory failed— PHP could not allocate the memory the JIT runs in, and turned it off
Every message has its page under the errors PHP prints.
The releases. What this page says of a PHP release comes from the sources: ext/pcre/php_pcre.c and the bundled ext/pcre/pcre2lib/pcre2.h at the release tags of php-src, the UPGRADING notes of PHP 8.2.0 and PHP 8.4.0, the pages of the PHP manual on the modifiers and on assertions, and the change log of PCRE2. Every line of code was then run on the official php:X.Y-cli images, 8.0 to 8.6, and prints what its comment says on every release it names.
Try it. Open /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/ in the playground: the Diagnostics tab shows what the linter says of it.
Learn more
- The tutorial: ten chapters, from the first pattern to recursion.
- The cookbook: ready-made patterns for emails, URLs, dates and more.
- PHP regex modifiers and preg_replace in PHP.
- Every message of the engine and its fix.