RegEx Modifiers

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 105 of 255

What Are Modifiers?

In simple terms: Modifiers are single letters placed after the closing delimiter of a pattern that change how the pattern is matched — for example, ignoring upper/lower case, or letting ^ and $ work on each line instead of the whole text.

Technically: Modifiers (also called flags) set PCRE options for the entire pattern. They are written directly after the closing delimiter, and several can be combined in any order: /pattern/imu.

preg_match('/^php$/i', 'PHP');   // i = case-insensitive

Overview

ModifierNameEffect
iCase-insensitiveLetters match regardless of case
mMultiline^ and $ match at the start and end of each line
sDotall. also matches newline characters
xExtendedWhitespace in the pattern is ignored, and # starts a comment
uUnicode (UTF-8)Pattern and subject are treated as UTF-8
DDollar end only$ matches only at the very end, not before a final newline
UUngreedyQuantifiers are lazy by default (and ? makes them greedy)
AAnchoredThe match must start at the beginning of the subject (or the given offset)
nNo auto-capture (PHP 8.2+)Plain (...) groups do not capture; named groups still do
JDuplicate namesAllows several groups with the same name

Removed: The e modifier (evaluate replacement as PHP code) was removed in PHP 7.0 because it caused security vulnerabilities. Use preg_replace_callback() instead.


i — Case-Insensitive

<?php
var_dump(preg_match('/^yes$/', 'YES'));
var_dump(preg_match('/^yes$/i', 'YES'));

Output

int(0)
int(1)

Without i, yes and YES are different. With i, the comparison ignores case. For non-ASCII letters (such as É and é), combine it with u.


m — Multiline

By default, ^ matches only at the start of the whole string and $ only at its end. With m, they also match at the start and end of every line:

<?php
$list = "Shopping:\n- Milk\n- Bread\n- Eggs";

echo preg_match_all('/^- (.+)$/', $list, $withoutM) . "\n";
echo preg_match_all('/^- (.+)$/m', $list, $withM) . "\n";

print_r($withM[1]);

Output

0
3
Array
(
    [0] => Milk
    [1] => Bread
    [2] => Eggs
)

Without m, the pattern requires the whole string to start with - , which it does not. With m, each list line is matched separately. This is essential for processing multi-line text such as logs, configuration files, or pasted lists.


s — Dot Matches Newlines

Normally, . matches any character except a newline. With s, it matches newlines too:

<?php
$html = "<p>Line one\nLine two</p>";

var_dump(preg_match('/<p>(.*)<\/p>/', $html));

preg_match('/<p>(.*)<\/p>/s', $html, $m);
var_dump($m[1]);

Output

int(0)
string(17) "Line one
Line two"

Without s, .* cannot cross the line break, so there is no match. With s, the content spanning both lines is captured.

m vs s

These two are often confused:

ModifierChanges
mThe meaning of ^ and $ (line by line)
sThe meaning of . (includes newlines)

They are independent and can be combined (/.../ms).


x — Extended Mode (Readable Patterns)

With x, whitespace inside the pattern is ignored and # starts a comment. Long patterns become readable and self-documenting:

<?php
$pattern = '/
    ^
    (?<state>[A-Z]{2})       # state code, e.g. TN
    (?<district>\d{2})       # district number
    (?<series>[A-Z]{1,2})    # series letters
    (?<number>\d{4})         # vehicle number
    $
/x';

preg_match($pattern, 'TN09AB1234', $m);

echo "{$m['state']} / {$m['district']} / {$m['series']} / {$m['number']}\n";

Output

TN / 09 / AB / 1234

To match a literal space or # in extended mode, escape it (\ , 0) or put it in a character class ([ ], [#]).


u — UTF-8 Mode

Without u, PCRE works on bytes. Characters outside ASCII — accented letters, Indian scripts, ₹, emoji — take several bytes in UTF-8, so . and quantifiers count bytes instead of characters:

<?php
var_dump(preg_match('/^.{4}$/', 'Café'));
var_dump(preg_match('/^.{4}$/u', 'Café'));

Output

int(0)
int(1)

Café has 4 characters but 5 bytes (é uses two). Only with u does .{4} count characters.

What u Enables

  • ., \X, and quantifiers operate on characters, not bytes.
  • Unicode properties such as \p{L} (any letter) and \p{Tamil} become usable.
  • Offsets reported by functions are still byte offsets.

Invalid UTF-8 With u

<?php
$result = preg_match('/\w+/u', "abc\xFF");

var_dump($result);
echo preg_last_error_msg() . "\n";

Output

bool(false)
Malformed UTF-8 characters, possibly incorrectly encoded

With u, the subject must be valid UTF-8; otherwise, the function fails and returns false. This is useful: it reveals encoding problems instead of silently producing wrong results. Always add u when processing user input that may contain non-ASCII text.


D — Dollar Matches Only at the Very End

<?php
var_dump(preg_match('/^\d+$/', "12345\n"));
var_dump(preg_match('/^\d+$/D', "12345\n"));

Output

int(1)
int(0)

By default, $ also matches before a newline at the end of the string, so "12345\n" passes a digits-only check. D closes that gap. (\z achieves the same effect within the pattern.) D is ignored if m is also set.


U — Ungreedy by Default

<?php
preg_match('/<.+>/', '<b>bold</b>', $greedy);
preg_match('/<.+>/U', '<b>bold</b>', $ungreedy);

echo $greedy[0] . "\n";
echo $ungreedy[0] . "\n";

Output

<b>bold</b>
<b>

U inverts greediness for the whole pattern, so .+ behaves like .+?. Because this reverses the usual meaning of ?, patterns with U are confusing to readers. Writing lazy quantifiers explicitly (.+?) is usually clearer.


n — No Automatic Capturing (PHP 8.2+)

<?php
preg_match('/(\d{4})-(\d{2})/', '2026-10', $normal);
preg_match('/(\d{4})-(?<month>\d{2})/n', '2026-10', $noCapture);

print_r($normal);
print_r($noCapture);

Output

Array
(
    [0] => 2026-10
    [1] => 2026
    [2] => 10
)
Array
(
    [0] => 2026-10
    [month] => 10
    [1] => 10
)

With n, plain parentheses only group; only named groups capture. This keeps the matches array small when parentheses are used only for grouping and alternation.


Inline Modifiers

Modifiers can be switched on for part of a pattern with (?flags) or (?flags:...):

<?php
$pattern = '/^Status: (?i:active|inactive)$/';

var_dump(preg_match($pattern, 'Status: ACTIVE'));
var_dump(preg_match($pattern, 'STATUS: active'));

Output

int(1)
int(0)

Only the group (?i:active|inactive) is case-insensitive. The label Status: must still match exactly.


Practical Example: Parsing a Simple Config Text

<?php
$text = <<<CONFIG
# Application settings
APP_NAME = GoCourse
app_debug= true

DB_PORT =3306
CONFIG;

$pattern = '/
    ^ \s*
    ([a-z_]+)        # key
    \s* = \s*
    (.*?)            # value (lazy)
    \s* $
/mix';

preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);

$config = [];
foreach ($matches as [, $key, $value]) {
    $config[strtoupper($key)] = $value;
}

print_r($config);

Output

Array
(
    [APP_NAME] => GoCourse
    [APP_DEBUG] => true
    [DB_PORT] => 3306
)

How the Modifiers Work Together

ModifierRole in This Pattern
m^ and $ apply to each line, so every setting is matched separately
i[a-z_] also accepts uppercase keys such as APP_NAME
xThe pattern is spread over several lines with comments
  • The comment line does not match, because # is not in [a-z_]. The empty line has no = and is skipped as well.
  • (.*?)\s*$ captures the value lazily, so trailing spaces are not included.
  • PREG_SET_ORDER groups each match's parts together, which allows destructuring in the foreach.

(For real configuration files, use parse_ini_file() or a .env library; the example demonstrates modifiers.)


Common Mistakes

Confusing m and s

Effect: Line anchors or dots do not behave as expected.

Fix: m changes ^/$; s changes ..

Forgetting u for Non-ASCII Text

Effect: Wrong lengths, broken characters, and \p{...} classes not working as expected.

Fix: Add u whenever text may contain non-ASCII characters.

Literal Spaces in x Mode

Effect: Spaces in the pattern are ignored, so /a b/x matches ab.

Fix: Escape spaces (\ ) or use [ ] or \s.

Using U and Then ?

Effect: .+? becomes greedy under U.

Fix: Avoid U; write lazy quantifiers explicitly.

Expecting $ to Reject a Trailing Newline

Effect: Values like "123\n" pass validation.

Fix: Use D or \z.


Best Practices

  • Use u for all user-facing text.
  • Use i instead of writing [Aa][Bb] alternatives.
  • Use m for line-by-line processing and s when . must cross lines.
  • Use x with comments for complex patterns.
  • Prefer explicit lazy quantifiers and \z over U and implicit end-of-string behavior.

Official reference: https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about RegEx Modifiers and get answers drawn from it.

Signed-in readers only.