Hide email address with stars (*)



PHP Snippet 1:

$minFill = 4;
echo preg_replace_callback(
         '/^(.)(.*?)([^@]?)(?=@[^@]+$)/u',
         function ($m) use ($minFill) {
              return $m[1]
                     . str_repeat("*", max($minFill, mb_strlen($m[2], 'UTF-8')))
                     . ($m[3] ?: $m[1]);
         },
         $email
     );

PHP Snippet 3:

/            #pattern delimiter
^            #start of string
(.)          #capture group #1 containing the first character
(.*?)        #capture group #2 containing zero or more characters (lazy, aka non-greedy)
([^@]?)      #capture group #3 containing an optional single non-@ character
(?=@[^@]+$)  #require that the next character is @ then one or more @ until the end of the string
/            #pattern delimiter
u            #unicode/multibyte pattern modifier

PHP Snippet 4:

$em = '[email protected]'; // 'a****[email protected]'
$em = '[email protected]'; // 'a*******[email protected]'

PHP Snippet 5:

$stars = 4; // Min Stars to use
$at = strpos($em,'@');
if($at - 2 > $stars) $stars = $at - 2;
print substr($em,0,1) . str_repeat('*',$stars) . substr($em,$at - 1);

PHP Snippet 6:

$email = "[email protected]";
print preg_replace_callback('/(\w)(.*?)(\w)(@.*?)$/s', function ($matches){
    return $matches[1].preg_replace("/\w/", "*", $matches[2]).$matches[3].$matches[4];
}, $email);

# a****[email protected]

PHP Snippet 7:

<?php
$string='[email protected]';
preg_match('/^.\K[a-zA-Z\.0-9]+(?=.@)/',$string,$matches);//here we are gathering this part bced

$replacement= implode("",array_fill(0,strlen($matches[0]),"*"));//creating no. of *'s
echo preg_replace('/^(.)'.preg_quote($matches[0])."/", '$1'.$replacement, $string);

PHP Snippet 8:

<?php
function hide_email($email) {
        // extract email text before @ symbol
        $em = explode("@", $email);
        $name = implode(array_slice($em, 0, count($em) - 1), '@');

        // count half characters length to hide
        $length = floor(strlen($name) / 2);

        // Replace half characters with * symbol
        return substr($name, 0, $length) . str_repeat('*', $length) . "@" . end($em);
}

echo hide_email("[email protected]");
?>