PHP – mb_ereg_replace() function – Replace regular expression with multibyte support

In PHP, mb_ereg_replace() is used to replace a regular expression with multibyte support. It scans the string for matches to pattern, then replaces the matched text with the replacement, making it ideal for handling international characters and Unicode strings.

Syntax

string mb_ereg_replace(string $pattern, string $replacement, string $string, string $options = null)

Parameters

The function accepts the following four parameters −

  • $pattern − The regular expression pattern. It may use multibyte characters in the pattern.

  • $replacement − The replacement text used to replace the matched pattern.

  • $string − The input string to be searched and modified.

  • $options − Optional search modifiers (like "i" for case-insensitive matching).

Return Values

mb_ereg_replace() returns the modified string on success, or FALSE on error. It returns NULL if the string is not valid for the current encoding.

Example 1: Basic Character Replacement

In this example, we'll replace lowercase "h" with uppercase "H" using UTF-8 encoding ?

<?php
   // Set regex encoding to UTF-8
   mb_regex_encoding("UTF-8");
   
   // Replace 'h' with 'H'
   $string = mb_ereg_replace("[h]", "H", "hello World");
   
   echo $string;
?>
Hello World

Example 2: Multibyte Character Replacement

This example demonstrates replacing Japanese characters using multibyte support ?

<?php
   mb_regex_encoding("UTF-8");
   
   // Replace Japanese character ? with ?????
   $text = "? is a Japanese character";
   $result = mb_ereg_replace("?", "?????", $text);
   
   echo $result;
?>
????? is a Japanese character

Example 3: Using Options Parameter

Here we use the options parameter for case-insensitive matching ?

<?php
   mb_regex_encoding("UTF-8");
   
   // Case-insensitive replacement using 'i' option
   $text = "PHP is Great and php is powerful";
   $result = mb_ereg_replace("php", "JavaScript", $text, "i");
   
   echo $result;
?>
JavaScript is Great and JavaScript is powerful

Conclusion

mb_ereg_replace() is essential for pattern replacement in multibyte strings, especially when working with international text. Always set the appropriate encoding with mb_regex_encoding() before using this function.

Updated on: 2026-03-15T09:59:46+05:30

794 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements