6

How can I convert username in email addresses into asterisks. The first and last letter in the username stay as it is and rest replaced with (*).

Example:

mhyunf@gmail.com

into

m****f@gmail.com
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
Sajid
  • 85
  • 2
  • 7
  • related: [Partially hiding an email address with PHP regex](http://stackoverflow.com/q/30233813) (and there are a few more [ugly explode/str_repeat answers](https://www.google.de/search?q=site:stackoverflow.com+php+replace+part+of+email+address+with+asterisks) on that topic) – mario Jul 08 '15 at 11:55

3 Answers3

16

You can do it using look arounds.

/(?!^).(?=[^@]+@)/
  • (?!^) Negative look behind. Checks if the character is not preceded by start of string. This ensures that the first character is not selected.

  • . Matches a single character.

  • (?=[^@]+@) Positive look ahead. Ensures that the single character matched is followed by anything other than @ ( ensured by [^@] ) and then a @

Regex Demo

Example

preg_replace("/(?!^).(?=[^@]+@)/", "*", "mhyunf@gmail.com")
=>  m****f@gmail.com
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0

Or alternatively if you don't wanna use regex you can do something like this

function filterEmail($email) {
    $emailSplit = explode('@', $email);
    $email = $emailSplit[0];
    $len = strlen($email)-1;
    for($i = 1; $i < $len; $i++) {
        $email[$i] = '*';
    }
    return $email . '@' . $emailSplit[1];
}
herriekrekel
  • 571
  • 6
  • 15
0
function hideEmail($email, $domain_ = false){

    $seg = explode('@', $email);
    $user = '';
    $domain = '';

    if (strlen($seg[0]) > 3) {
        $sub_seg = str_split($seg[0]);
        $user .= $sub_seg[0].$sub_seg[1];
        for ($i=2; $i < count($sub_seg)-1; $i++) { 
            if ($sub_seg[$i] == '.') {
                $user .= '.';
            }else if($sub_seg[$i] == '_'){
                $user .= '_';
            }else{
                $user .= '*';
            }
        }
        $user .= $sub_seg[count($sub_seg)-1];
    }else{
        $sub_seg = str_split($seg[0]);
        $user .= $sub_seg[0];
        for ($i=1; $i < count($sub_seg); $i++) { 
            $user .= ($sub_seg[$i] == '.') ? '.' : '*';
        }
    }

    $sub_seg2 = str_split($seg[1]);
    $domain .= $sub_seg2[0];
    for ($i=1; $i < count($sub_seg2)-2; $i++) { 
        $domain .= ($sub_seg2[$i] == '.') ? '.' : '*';
    }

    $domain .= $sub_seg2[count($sub_seg2)-2].$sub_seg2[count($sub_seg2)-1];

    return ($domain_ == false) ? $user.'@'.$seg[1] : $user.'@'.$domain ;

}
Gabriel Glauber
  • 961
  • 11
  • 9