Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially hide email address in PHP

Tags:

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 [email protected] to become abcdl******@hotmail.com.

As a test I wrote:

<?php $email = "[email protected]";  $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; 

This works, but I was wondering if there was any easier/shorter way of applying the same logic? Like a regex maybe?

like image 951
Bluemagica Avatar asked Dec 12 '13 13:12

Bluemagica


People also ask

Can you use an asterisk in an email address?

You can use the asterisk (*) as a wildcard in email addresses when defining routes and in file names. Wildcards can appear in the name or domain sections of an email address. The following are valid examples: *@*: Valid representation of all email addresses.


1 Answers

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()

like image 75
msturdy Avatar answered Oct 27 '22 01:10

msturdy