How to obfuscate a PHP email by filling part of the characters before @ (arroba) with * (asterisk)?

Asked

Viewed 840 times

1

I need to obfuscate the characters of the email, as I’ve seen many websites doing, by 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 in a very simple way?

  • PS: I thought maybe using the substr_replace was a good idea

3 answers

3

I thought of crafting in a very simple way using the function substr_replace combined with strpos.

Behold:

$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) makes the position to be replaced from the first character. The fourth argument strpos($mail, '@') will give us the final position where it should be replaced, which is the @. In that case, I used the -2 so that neither the @ nor the last character before it was replaced.

The size of the replacement will be determined from the initial position. If it was 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); 

2

Can use sub_str_replace() to start where and how many characters to replace and str_repeat() to generate the string that replaces 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);
  • Man, nice solution, but I think you should adapt it in a way that stays before the @

  • @Wallacemaxters soon I’ll get it right.

1

You can also do through the function preg_replace.

With the 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 quite specific rules for 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 function preg_replace_callback and work more freely using a specific function for a particular 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;
}

Demonstration

Browser other questions tagged

You are not signed in. Login or sign up in order to post.