A simple string obscure function in PHP
It’s quite common to need to obscure sensitive information when displaying it to
a client. For example, it’s safer to display a user’s email address as
h***.g****@g****.c**
. If someone views the page, the user’s personal
information isn’t fully revealed, but the user can still confirm that it’s
correct.
This post is just a note of a helper function to do this in PHP.
<?php
/**
* @param string|string[] $plain
* @param int $revealStart
* @param int $revealEnd
* @param string $obscuration
*
* @return string|string[]
*/
function obscure(
$plain,
int $revealStart = 1,
int $revealEnd = 0,
string $obscuration = '*'
) {
if (is_array($plain)) {
return array_map(
function ($plainPart) use ($revealStart, $revealEnd, $obscuration) {
return obscure($plainPart, $revealStart, $revealEnd, $obscuration);
},
$plain
);
}
$plain = (string) $plain;
return mb_substr($plain, 0, $revealStart)
. str_repeat(
$obscuration,
max(
0,
mb_strlen($plain) -
($revealStart + $revealEnd)
)
)
. mb_substr(
$plain,
-$revealEnd,
$revealEnd
);
}
Note that the function can take an array of strings and call itself recursively on them if necessary.
The helper function below uses that obsure()
function to obscure an email
address specifically:
<?php
function obscureEmailAddress(
string $emailAddress,
int $revealStart = 1,
int $revealEnd = 0,
string $obscuration = '*'
): string {
$userNameDomain = explode('@', $emailAddress, 2);
while (count($userNameDomain) < 2) {
$userNameDomain[] = '';
}
return sprintf(
'%s@%s',
implode(
'.',
obscure(explode('.', $userNameDomain[0]), $revealStart, $revealEnd, $obscuration)
),
implode(
'.',
obscure(explode('.', $userNameDomain[1]), $revealStart, $revealEnd, $obscuration)
)
);
}
This individually obscures separate parts of the email address for a better overall effect.