In PHP, when working with multibyte strings, if you need to perform a case-insensitive string replacement, mb_eregi_replace is a very useful function. It not only supports multibyte character sets (such as UTF-8), but it can also perform replacement operations using regular expressions while ignoring case differences.
mb_eregi_replace is one of the multibyte string regular expression replacement functions in PHP, similar to eregi_replace, but specifically designed for multibyte encodings. The function prototype is as follows:
mb_eregi_replace(string $pattern, string $replacement, string $string, ?string $encoding = null): string|false
$pattern: The regular expression pattern to match (case-insensitive)
$replacement: The replacement content
$string: The target string to search and replace
$encoding: The string encoding, default is the internal character encoding, usually set to "UTF-8"
Supports multibyte encodings
Standard regular expression replacement functions cannot correctly handle multibyte characters like Chinese or Japanese, whereas mb_eregi_replace ensures no garbled text.
Case-insensitive matching
mb_eregi_replace performs case-insensitive matching by default, eliminating the need to manually add the i modifier.
Regular expression flexibility
It supports the full range of regular expression patterns, making it more powerful.
Suppose we have a string, and we want to replace all occurrences of "php" in different cases with "PHP Language". Here's how you can do it:
<?php
// Original string
$text = "Php is a popular scripting language. I love php and PHP.";
<p>// Using mb_eregi_replace for case-insensitive replacement<br>
$result = mb_eregi_replace("php", "PHP语言", $text, "UTF-8");</p>
<p>echo $result;<br>
?><br>
The output will be:
PHP语言 is a popular scripting language. I love PHP语言 and PHP语言.
As you can see, "Php", "php", and "PHP" were all correctly replaced.
Website content filtering (case-insensitive replacement of sensitive words)
Multilingual text processing
String formatting and normalization
PHP version support
mb_eregi_replace may not be recommended in some newer versions of PHP, so it's recommended to check the PHP manual for compatibility.
Performance concerns
Regular expression matching has lower performance compared to simple string replacements. If the requirement is just simple case-insensitive replacement, other methods may be more efficient.
Encoding consistency
Ensure that the encoding of the target string and the one used by the function match to avoid garbled text.
For more information about mb_eregi_replace, refer to the official PHP manual: