Partially hide email address in PHP
here's something quick:
function obfuscate_email($email)
{
$em = explode("@",$email);
$name = implode('@', array_slice($em, 0, count($em)-1));
$len = floor(strlen($name)/2);
return substr($name,0, $len) . str_repeat('*', $len) . "@" . end($em);
}
// to see in action:
$emails = ['"Abc\@def"@iana.org', 'abcdlkjlkjk@hotmail.com'];
foreach ($emails as $email)
{
echo obfuscate_email($email) . "\n";
}
echoes:
"Abc\*****@iana.org
abcdl*****@hotmail.com
uses substr()
and str_repeat()
Hint or partially hide email address with stars (*) in PHP
At first, I thought that strpos()
on @
would get me the length of the "local" part of the address and I could use substr_replace()
to simply inject the asterisks BUT a valid email address can have multiple @
in the local part AND multibyte support is a necessary inclusion for any real-world project. This means that mb_strpos()
would be an adequate replacement for strpos()
, but there isn't yet a native mb_substr_replace()
function in php, so the convolution of devising a non-regex snippet became increasingly unattractive.
If you want to see my original answer, you can check the edit history, but I no longer endorse its use. My original answer also detailed how other answers on this page fail to obfuscate email addresses which have 1 or 2 characters in the local substring. If you are considering using any other answers, but sure to test against a@example.com
and ab@example.com
as preliminary unit tests.
My snippet to follow DOES NOT validate an email address; it is assumed that your project will use appropriate methods to validate the address before bothering to allow it into your system. The power/utility of this snippet is that it is multibyte-safe and it will add asterisks in all scenarios and when there is only a single character in the local part, the leading character is repeated before the @
so that the mutated address is harder to guess. Oh, and the number of asterisks to be added is declared as a variable for simpler maintenance.
Code: (Demo) (Regex Demo)
$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
);
Input/Output:
'a@example.com' => 'a****a@example.com',
'ab@example.com' => 'a****b@example.com',
'abc@example.com' => 'a****c@example.com',
'abcd@example.com' => 'a****d@example.com',
'abcde@example.com' => 'a****e@example.com',
'abcdef@example.com' => 'a****f@example.com',
'abcdefg@example.com' => 'a*****g@example.com',
'Ф@example.com' => 'Ф****Ф@example.com',
'ФѰ@example.com' => 'Ф****Ѱ@example.com',
'ФѰД@example.com' => 'Ф****Д@example.com',
'ФѰДӐӘӔӺ@example.com' => 'Ф*****Ӻ@example.com',
'"a@tricky@one"@example.com' => '"************"@example.com',
Regex-planation:
/ #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
Callback explanation:
$m[1]
the first character (capture group #1)str_repeat("*", max($minFill, mb_strlen($m[2], 'UTF-8')))
measure the multibyte length of capture group #2 usingUTF-8
encoding, then use the higher value between that calculated length and the declared$minFill
, then repeat the character*
the number of times returned from themax()
call.($m[3] ?: $m[1])
the last character before the@
(capture group #3); if the element is empty in the$m
array, then use the first element's value -- it will always be populated.
How to get the partial email address in javascript and PHP
Here is JS:
const firstAndLast = str => {
const firstChar = str.substring(0,3);
const lastChar = str.slice(-1);
return [firstChar, lastChar]
}
const firstThird = str => {
const strArray = str.split(".");
const result = []
for (let i = 0; i < (strArray[0].length + 1)/3; i++) {
result.push(str[i])
}
return [result.join(''), strArray[1]]
}
const str = "tsadsadsadsajhuhuhuy@gmail.com"
const strArray = str.split("@");
const [userFirst, userLast] = firstAndLast(strArray[0])
const [domainFirst, domainLast] = firstThird(strArray[1])
console.log(`${userFirst}****${userLast}@${domainFirst}***.${domainLast}`)
Here is PHP:
<?php
function firstAndLast($str) {
$firstChar = substr($str, 0, 3);
$lastChar = substr($str, -1);
return [$firstChar, $lastChar];
}
function firstThird($str) {
$strArray = explode(".", $str);
$result = [];
$str_length = (strlen($strArray[0]) + 1)/3;
for ($i = 0; $i < $str_length; $i++) {
array_push($result, $str[$i]);
}
return [implode('', $result), $strArray[1]];
}
$str = "tsadsadsadsajhuhuhuy@gmail.com";
$strArray = explode("@", $str);
$user = firstAndLast($strArray[0]);
$domain = firstThird($strArray[1]);
echo $user[0].'****'.$user[1].'@'.$domain[0].'***.'.$domain[1];
Both turn your example email into:
tsa****y@gm***.com
Partially hiding an email address with PHP regex
You can use:
$email = preg_replace('/(?:^|@).\K|\.[^@]*$(*SKIP)(*F)|.(?=.*?\.)/', '*', $email);
RegEx Demo
This will turn great@gmail.com
into g*****@g*****.com
and
myemail@gmail.co.uk
will become m*******@g*****.co.uk
and test.test@gmail.com
into t*********@g*****.com
How Can I hide part of my E-mail Address
Use RegEx to always match the e-mail username :
echo preg_replace('/.*@/', '***@', 'some_mail@somewhere.net');
Partially hide email address in TypeScript(Javascript)
As stated above, this really isn't a JavaScript job, but here's something short to get you started:
var censorWord = function (str) {
return str[0] + "*".repeat(str.length - 2) + str.slice(-1);
}
var censorEmail = function (email){
var arr = email.split("@");
return censorWord(arr[0]) + "@" + censorWord(arr[1]);
}
console.log(censorEmail("jack.dawson@gmail.com"));
j*********n@g*******m
Partially hide email addresses with PHP regular expression?
It is ..
- matching (and skipping)
"@"
and then; - matching
.
(any character: i.e. the"d"
in"domain"
) and then; - matching 0 (zero) of the following character class, which is the minimum it needed to match the supplied regular expression.
That is, the first and only the first character after the @
was matched and replaced with ~
.
The following
(?<=@.)[a-zA-Z0-9-]*(?=(?:[.]|$))
forces the character class to match to the first "."
(period, as in ".com"
) or end-of-input.
Note that the .
is moved inside of the (?<=@.)
-look-behind clause which causes it to skip the first letter after the "@"
. I have also added a hyphen ("-"
) to the character class as they are valid (and not terribly uncommon) in domain names.
In addition, not all email addresses are in the trivial "a@b.c"
form and Internationalized Domain Names (or IDN) can be represented locally in a non-punycode form when not transmitted (e.g. not used in a restricting context), but that is another topic. (It may be more appropriate to replace [a-zA-Z0-9-]*
with [^.]*
due to IDN without further specification.)
How can hide the email address
<table class="table table-striped text-center"><thead><tr>
<th scope="col">Username</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<?php
foreach ($withdrawHistory as $wd) {
echo '<tr><td>' . $wd["username"] . '</td>
<td>' . '****'.strstr($wd["wallet"], '@') . '</td>
</tr>'; }?> </tbody></table>
Related Topics
Fix iOS Picture Orientation After Upload PHP
Class 'App\Http\Controllers\Db' Not Found and I Also Cannot Use a New Model
.Htaccess Redirect Non-Www to Www Preserving Uri String
Multidimensional Array PHP Implode
How to Strip Out the Domain Name from a Url in PHP
What Does [\S\S]* Mean in Regex in PHP
Move an Array Element to a New Index in PHP
How to Put My Wamp Online for Someone to Access
Get the Metadata of an Order Item in Woocommerce 3
PHP - Detect Whitespace Between Strings
Copy Large Files (Over 2 Gb) in PHP
Doctrine2 Association Mapping with Conditions
Compress/Archive Folder Using PHP Script