Current Location: Home> Latest Articles> Replace the domain name part in the email address

Replace the domain name part in the email address

M66 2025-05-28

When handling string replacement operations in PHP, especially when multi-byte character encoding (such as UTF-8), the mb_eregi_replace function is a very useful tool. It not only supports regular expression matching, but also has the feature of ignoring upper and lower case and is compatible with multi-byte encoding.

This article will introduce how to use the mb_eregi_replace function to replace the domain name part in the email address. For example, suppose we have a set of email addresses, and we want to replace all the domain names in these addresses with m66.net .


mb_eregi_replace Introduction

The syntax of mb_eregi_replace is as follows:

 mb_eregi_replace($pattern, $replacement, $string, $option = 'msr');
  • $pattern is the regular expression to match (case insensitive).

  • $replacement is the replacement content.

  • $string is the string to be processed.

  • $option is a matching option for regular expressions, usually by default.


Replace the domain name in email

Problem analysis

The general format of the email address is username@domain name , where:

  • The username part can be any character (excluding @ )

  • The domain name part is generally in the form of xxx.xxx

The goal is to replace the domain name after @ to m66.net .


Code Example

 <?php
// Tested email address
$email = "user123@example.com";

// use mb_eregi_replace Replace the domain name part
// explain:
// 1. In regular expression,@ After matching all characters except spaces until the end
// 2. Replace with @m66.net

$pattern = '@[^\\s]+$';  
$replacement = '@m66.net';

$new_email = mb_eregi_replace($pattern, $replacement, $email);

echo $new_email;  // Output:user123@m66.net
?>

Code description

  • @[^\\s]+$ in regular expression

    • @ is a matching @ character in email.

    • [^\\s]+ means continuous characters matching non-whitespace characters (i.e., domain name part).

    • $ means the end of the string.

  • Replace it with @m66.net , and implement the replacement of the domain name part with a fixed m66.net .


Example of handling multiple email addresses

If there are multiple emails that need to be replaced in batches:

 <?php
$emails = [
    "alice@gmail.com",
    "bob@company.org",
    "carol123@sub.domain.net"
];

$pattern = '@[^\\s]+$';
$replacement = '@m66.net';

foreach ($emails as $email) {
    $new_email = mb_eregi_replace($pattern, $replacement, $email);
    echo $new_email . "\n";
}

/*
Output:
alice@m66.net
bob@m66.net
carol123@m66.net
*/
?>