Regex tester · Guide

Regex Flags PHP: Modifiers in preg_ Functions

PHP puts regex flags after the closing delimiter rather than in a separate argument. Most map to what you know from other languages, with one notable absence and one modifier you should almost always add.

The modifiers

PHP
preg_match('/hello/i',  $s);   // case-insensitive
preg_match('/^x/m',     $s);   // ^ and $ match at line breaks
preg_match('/a.b/s',    $s);   // dot matches newline (dotall)
preg_match('/a b/x',    $s);   // ignore whitespace, allow # comments
preg_match('/café/u',   $s);   // UTF-8 mode

They combine freely: /pattern/imsu. The delimiter does not have to be / — using # or ~ avoids escaping slashes in a pattern full of URLs or paths.

There is no g flag

The g modifier is a JavaScript concept. In PHP the function decides: preg_match finds the first match, preg_match_all finds all of them.

Similarly preg_replace replaces every occurrence by default, with a $limit argument to restrict it. A /g copied from JavaScript into a PHP pattern produces "Unknown modifier" — one of the most common PHP regex errors.

Always consider the u modifier

Without u, PCRE treats the subject as single bytes. A multi-byte character is several separate bytes, so . matches half a character and a character class can split one:

PHP
preg_match('/^.$/',  'é');   // 0 — two bytes, not one character
preg_match('/^.$/u', 'é');   // 1 — correct

With u, \w and \b still stay ASCII unless you enable Unicode properties. Combining u with \p{L} is the reliable way to match letters in any script.

One caveat: with u, PCRE validates the subject as UTF-8 and preg_match returns false on invalid input rather than 0. Check for false explicitly, or malformed input looks like "no match".

Inline and scoped flags

Flags also work inside the pattern: (?i) from that point on, (?i:...) for a group only. Useful when the pattern comes from configuration and you cannot add modifiers.

For performance, note that preg_ functions cache compiled patterns internally, so there is no preg_compile and no need to build one yourself.

Frequently asked questions

Why does PHP say "Unknown modifier g"?

PHP has no g flag. Use preg_match_all for all matches.

Do I need the u modifier?

Whenever the subject may contain non-ASCII text. Without it PCRE works byte by byte.

Why does preg_match return false?

An error occurred — commonly invalid UTF-8 with the u modifier. false is not the same as 0.

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool