Multibyte strings7 min readExamples run on PHP 8.5.10

mb_ereg_replace()

Learn how mb_ereg_replace() replaces regular expression matches in multibyte text, with its PHP 8.4 signature, return values, examples and pitfalls.

Signature

mb_ereg_replace(string $pattern, string $replacement, string $string, ?string $options = null): string|false|null
Available since PHP 4.2.07.48.08.18.28.38.48.5All versions →

Purpose

mb_ereg_replace() searches a string for matches of a regular expression and replaces each match with a replacement text. It belongs to the mbstring regex family, so it treats the subject as a sequence of characters in the current regex encoding rather than as raw bytes. A pattern such as . therefore matches one whole character like é or я, not a single byte of it.

Unlike the preg_* functions, the pattern is written without delimiters, and flags are passed as a separate options string.

Signature

Parameters and defaults

  • $pattern: the regular expression. It may contain multibyte characters. Do not wrap it in /.../.
  • $replacement: the replacement text. Backreferences to capture groups are written as \1, \2 and so on. In a single-quoted PHP string, '\1' is passed through as a backslash followed by a digit, which is what you want.
  • $string: the subject text to search.
  • $options: an optional string of option letters, as described for mb_regex_set_options(). The default is null, which means the currently configured options are used. Since PHP 8.0 this parameter is explicitly nullable.

The character encoding comes from the internal encoding or from whatever mb_regex_encoding() has set. Calling mb_regex_encoding('UTF-8') at the start of a script makes your intent clear.

Return value and failure cases

  • A string with the replacements applied on success. If nothing matches, you get the subject back unchanged.
  • false if an error occurs, for example when the pattern cannot be compiled.
  • null if the subject is not valid for the current encoding.

Because there are three kinds of result, compare with === false or === null when you need to detect problems, and do not rely on truthiness: an empty string is a valid, falsy result.

Example 1: collapsing whitespace

A common cleanup is replacing runs of whitespace with one space. The multibyte text passes through untouched.

Example
<?php
mb_regex_encoding('UTF-8');
$text = "Привет,   мир \t  from   PHP";
$clean = mb_ereg_replace('\s+', ' ', $text);
echo json_encode($clean, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Привет, мир from PHP"

Example 2: reordering with backreferences

Parentheses capture parts of the match, and \1, \2 insert them into the replacement. Here a "Last, First" name becomes "First Last", including non-ASCII letters.

Example
<?php
mb_regex_encoding('UTF-8');
$name = "Müller, Åsa";
$swapped = mb_ereg_replace('^([^,]+), (.+)$', '\2 \1', $name);
echo json_encode($swapped, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Åsa Müller"

Example 3: case-insensitive matching with options

Passing 'i' as the fourth argument ignores case for that call. The accented word is left alone.

Example
<?php
mb_regex_encoding('UTF-8');
$text = "Café php PHP Php";
$result = mb_ereg_replace('php', 'PHP', $text, 'i');
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Café PHP PHP PHP"

Edge cases

  • No match: the original string is returned, not false.
  • Empty subject: an empty string comes back as an empty string.
  • Unmatched groups: a backreference to a group that did not take part in the match is replaced with nothing, so check your pattern when output looks too short.
  • Encoding mismatch: if the regex encoding does not match the real encoding of your data, matching can behave oddly or the function can return null.
  • Replacement text is not a literal: a backslash followed by a digit in the replacement is interpreted as a backreference. If your replacement comes from user input, escape backslashes first.

Common mistakes

  1. Adding delimiters. Writing '/\s+/' makes the slashes part of the pattern. Write '\s+'.
  2. Using $1 instead of \1. This function uses the backslash form.
  3. Using double-quoted strings carelessly. "\1" in double quotes is the control character with octal code 1, not a backreference. Use single quotes or write "\\1".
  4. Ignoring false and null. Treat them as distinct failures instead of assuming a string.
  5. Using the e option. It evaluates the replacement as code, offers no automatic escaping, and is dangerous on untrusted input. Never use it. Reach for mb_ereg_replace_callback() when you need computed replacements.
  6. Expecting preg_replace() flags. Option letters differ between the two families, so consult mb_regex_set_options().
  • mb_eregi_replace(): the same operation, ignoring case.
  • mb_regex_encoding(): gets or sets the regex character encoding.
  • mb_regex_set_options(): describes the option letters.
  • mb_ereg_replace_callback(): replaces using a callback.
  • preg_replace(): the PCRE alternative, which uses delimiters and the u modifier for UTF-8.

Recap

mb_ereg_replace() performs regex replacement on characters, not bytes. Give it a delimiter-free pattern, use \1-style backreferences, set the encoding explicitly, and check for false and null return values.

Tested examples

Collapse whitespace in multibyte text
<?php
mb_regex_encoding('UTF-8');
$text = "Привет,   мир \t  from   PHP";
$clean = mb_ereg_replace('\s+', ' ', $text);
echo json_encode($clean, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Привет, мир from PHP"
Reorder a name with backreferences
<?php
mb_regex_encoding('UTF-8');
$name = "Müller, Åsa";
$swapped = mb_ereg_replace('^([^,]+), (.+)$', '\2 \1', $name);
echo json_encode($swapped, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Åsa Müller"
Case-insensitive replacement with the options argument
<?php
mb_regex_encoding('UTF-8');
$text = "Café php PHP Php";
$result = mb_ereg_replace('php', 'PHP', $text, 'i');
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
"Café PHP PHP PHP"