Sajid
Sajid

Reputation: 85

Replace username part in email addresses into asterisks

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:

[email protected]

into

m****[email protected]

Upvotes: 6

Views: 4243

Answers (3)

Gabriel Glauber
Gabriel Glauber

Reputation: 971

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 ;

}

Upvotes: 0

herriekrekel
herriekrekel

Reputation: 571

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];
}

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

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("/(?!^).(?=[^@]+@)/", "*", "[email protected]")
=>  m****[email protected]

Upvotes: 16

Related Questions