Partially hide email address in PHP

Sometimes you must show an email address but not the full address. A masked email shows only a part, for example robin*****@example.com.

When do you need it?

  • In a password reset page, to give a hint about the registered email, like “We sent a link to ro***@example.com”.
  • In a profile or an order page, where you want to show the email but not to give it to spam bots.
  • In logs and admin lists, to protect the privacy of users.

PHP function to hide an email address

The function keeps the first half of the name part (before the @) and replaces the other half with the mask character. The domain is not changed.

<?php
function maskEmail(string $email, string $mask = "*"): string
{
    $parts = explode("@", $email, 2);

    // Not a valid email, return it as it is
    if (count($parts) !== 2) {
        return $email;
    }

    [$name, $domain] = $parts;

    $length  = mb_strlen($name);
    $visible = (int) floor($length / 2);

    return mb_substr($name, 0, $visible)
         . str_repeat($mask, $length - $visible)
         . "@" . $domain;
}

echo maskEmail("robin.kumar@example.com") . "<br>";
echo maskEmail("jo@example.com") . "<br>";
echo maskEmail("a@example.com");
?>

Output:

Tutorials Class - Output Window

robin******@example.com
j*@example.com
*@example.com

How it works

  • explode("@", $email, 2) splits the address into the name and the domain.
  • The visible part is half of the length of the name (floor($length / 2)). The rest is replaced using str_repeat().
  • mb_strlen() and mb_substr() are used, so names with non-English letters also work.

Why not hide a fixed number of characters?

If you always hide 5 characters, a short name like “jo” will be hidden fully, and a long name will show too much. Taking half of the length works well for every size.

Note: Masking is for display only. Do not save the masked value in the database, and do not use it to find a user. Always keep the real email safely, and print any email with htmlspecialchars().

Related: PHP String Handling and strlen() vs mb_strlen().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.