• support@answerspoint.com

Partially hide email address in PHP

2795

I am building a simple friend/buddy system, and when someone tries to search for new friends, I want to show partially hidden email addresses, so as to give an idea about who the user might be, without revealing the actual details.

So I want abcdlkjlkjk@gmail.com to become abcdl******@gmail.com.

As a test I wrote:

<?php
$email = "abcdlkjlkjk@gmail.com";

$em = explode("@",$email);
$name = $em[0];
$len = strlen($name);
$showLen = floor($len/2);
$str_arr = str_split($name);
for($ii=$showLen;$ii<$len;$ii++){
    $str_arr[$ii] = '*';
}
$em[0] = implode('',$str_arr); 
$new_name = implode('@',$em);
echo $new_name;
  • PHP

  • asked 8 years ago
  • G John

2Answer


0

This is better

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', 'abcdlkjlkjk@gmail.com'];

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

echoes:

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

uses substr() and str_repeat()

  • answered 8 years ago
  • Community  wiki

0
echo preg_replace('/(?<=.).(?=.*@)/u','*','TestEmail@gmail.com');

Will return

T********@gmail.com
  • answered 8 years ago
  • Community  wiki

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 2795 times
  • active 8 years ago

Best Rated Questions