Replace username part in email addresses into asterisks

三世轮回 提交于 2021-02-16 08:52:52

问题


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

回答1:


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



回答2:


You can replace the following regex :

/^([a-zA-Z])[^@]*([a-zA-Z].*)$/

with :

/\1****\2/



回答3:


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



回答4:


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 ;

}


来源:https://stackoverflow.com/questions/31291805/replace-username-part-in-email-addresses-into-asterisks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!