Partially hide email address in PHP

here’s something quick:

function obfuscate_email($email)
{
    $em   = explode("@",$email);
    $name = implode('@', array_slice($em, 0, count($em)-1));
    $len  = floor(strlen($name)/2);

    return substr($name,0, $len) . str_repeat('*', $len) . "@" . end($em);   
}

// to see in action:
$emails = ['"Abc\@def"@iana.org', '[email protected]'];

foreach ($emails as $email) 
{
    echo obfuscate_email($email) . "\n";
}

echoes:

"Abc\*****@iana.org
abcdl*****@hotmail.com

uses substr() and str_repeat()

Leave a Comment