很多时候,不需要直接显示全部邮箱在前端上,需要做适当的替换。
然而,邮箱的长度是不一样的,所以,需要对长度做不一样的替换,例如替换成星号*。
下面就是php的实现算法,采用正则表达式。
static function formatEmail($email)
{
$arr = explode("@", $email);
if (strlen($arr[0]) > 3 && strlen($arr[0]) <= 6){
return preg_replace('/(.{1})(.*?)(.{1})@(.*)/i', '$1***$3@$4', $email);
}elseif (strlen($arr[0]) <=3){
return preg_replace('/(.{1})(.*?)@(.*)/i', '$1***@$3', $email);
}
return preg_replace('/(.{3})(.*?)(.{3})@(.*)/i', '$1***$3@$4', $email);
}
另外,还有一种直接替换的方式:
public static function substr_replace($str, $replacement = "*", $start = 1, $length = 6)
{
$len = mb_strlen($str,"utf-8");
if ($len > intval($start+$length)) {
$str1 = mb_substr($str,0,$start,"utf-8");
$str2 = mb_substr($str,intval($start+$length),NULL,"utf-8");
} else {
$str1 = mb_substr($str,0,1,"utf-8");
$str2 = mb_substr($str,$len-1,1,"utf-8");
$length = $len - 2;
}
$new_str = $str1;
for ($i = 0; $i < $length; $i++) {
$new_str .= $replacement;
}
$new_str .= $str2;
return $new_str;
}
好了本文全部内容介绍完毕。