douzhuo3233 2017-03-26 23:37
浏览 19

如何使用PHP部分屏蔽/隐藏电子邮件地址

Im trying to achieve the following with PHP

sample@gmail.com           => s*****@gmail.com
sa@yahoo.com               => **@yahoo.com
sampleaddress@hotmail.com  => samplead*****@hotmail.com

I want to hide last five characters in the portion that stays before '@'

I can write long code to do this by splitting and then replacing based on lengths, but Im sure there must be an easy way to do this using PHP functions, any help please?

UPDATE:
Im adding my code here, Im sure its not efficient, and thats the reason Im asking it here

$email = 'sampleuser@gmail.com';
$star_string = '';
$expl_set = explode('@',$email);
if(strlen ($expl_set[0]) > 5){$no_stars = 5; }else{$no_stars = strlen ($expl_set[0]); }
for($i=0;$i<$no_stars; $i++)
{
    $star_string.='*'; 
}

$masked_email =  substr($expl_set[0], 0, -5).$star_string.'@'.$expl_set[1];
  • 写回答

1条回答 默认 最新

  • doujiao8649 2017-03-27 00:16
    关注

    You can wrap it into a function, making it easier to call multiple times.

    Basically, split the address and the domain, replace $mask number of characters in the end of the string (default 5) with *, or the length of the address if it's shorter than the amount of masked characters.

    function mask_email($email, $masks = 5) {
        $array = explode("@", $email);
        $string_length = strlen($array[0]);
        if ($string_length < $masks)
            $masks = $string_length;
        $result = substr($array[0], 0, -$masks) . str_repeat('*', $masks);
        return $result."@".$array[1];
    }
    

    The above would be used like this

    echo mask_email("test@test.com")."
    ";
    echo mask_email("longeremail@test.com");
    

    which would ouput this

    ****@test.com
    longer*****@test.com

    You can also specify the number you want filtered by using the second parameter, which is optional.

    echo mask_email("longeremail@test.com", 2); // Output: longerema**@test.com
    

    Live demo

    评论

报告相同问题?

悬赏问题

  • ¥20 C# TCP服务端,客户端退出后,不断有数据进来
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?