How to obfuscate an e-mail in PHP by filling in some of the characters before @ (at) with * (asterisks)?

1

I need to obfuscate the characters of the email, as I have seen many websites doing, filling some characters of this email with an asterisk.

I would like the code to be as complete as possible.

Example:

 '[email protected]' => 'wa*********[email protected]'

How to do this quite simply?

    
asked by anonymous 20.01.2018 / 13:08

3 answers

2

I thought of working very simply using the substr_replace function combined with strpos .

See:

$mail = '[email protected]'

substr_replace($mail, '*****', 1, strpos($mail, '@') - 2); 

The result is

'w*****[email protected]'

The explanation of the code is as follows: The third argument ( 1 ) causes the position to be replaced to be from the first character. The fourth argument strpos($mail, '@') will give us the final position where it should be replaced, which is @ . In this case, I used -2 so that neither the @ nor the last character before it was replaced.

Replacement size will be determined from the starting position. If it were necessary to display 2 characters at the beginning and 2 before the @ , we would have to change the function as follows:

substr_replace($mail, '*****', 2, strpos($mail, '@') - 4); 
    
20.01.2018 / 13:23
2

You can use sub_str_replace() to figure out where and how many characters to replace and str_repeat() to generate the string that will replace the original email.

function ofuscaEmail($email, $inicio, $qtd){
  $asc = str_repeat('*', $qtd);
  return substr_replace($email, $asc, $inicio, $qtd);
}

$str = '[email protected]';
echo ofuscaEmail($str, 2, 8);
    
20.01.2018 / 13:33
1

You can also do this through the preg_replace .

With regex below you can group the first two characters and the two characters before the @ .

^([\w_]{2})(.+)([\w_]{2}@)

With the power of regex you can create rules that are quite specific to your problem.

<?php

$pattern     = "/^([\w_]{2})(.+)([\w_]{2}@)/u";
$replacement = "$1********$3";
$email       = "[email protected]";

echo preg_replace($pattern, $replacement, $email);

//Output: wa********[email protected]

And with the same regex , you can also use the preg_replace_callback and work with more freedom using a specific function for a given problem.

<?php

function ocultarEmail($matches)
{
    return $matches[1] .
        str_repeat("*", strlen($matches[2])) .
        $matches[3];
}

$pattern     = "/^([\w_]{2})(.+)([\w_]{2}@)/u";

for($i = 1; $i <= 20; $i++) {
    $email       = str_repeat("a", $i)."@teste.com";
    echo preg_replace_callback($pattern, 'ocultarEmail', $email);
    echo PHP_EOL;
}

Demo

    
20.01.2018 / 18:37