3 回答
TA贡献1871条经验 获得超8个赞
我的简单 JavaScript 解决方案:
let email = document.getElementById("email").innerHTML;
//You should validate email format before proceeding
let parts = email.split("@");
let name = parts[0];
let tld = parts[1];
let censored = name.charAt(0) + "****" + name.charAt(name.length-1)
let result = censored + "@" + tld.substring(0, Math.floor(1/3*tld.length));
document.getElementById("censored").innerHTML = result;
<span id="email">thisismytestname@example.com</span><br>
<span id="censored"></span>
PHP 解决方案工作方式基本相同:
<?php
$email = "myemail@test.com";
//Should validate email format before proceeding
$parts = explode("@", $email);
$name = $parts[0];
$tld = $parts[1];
$censored = substr($name, 0, 1) . "****" . substr($name,-1);
$result = $censored . "@" . substr($tld, 0, floor(1/3*strlen($tld)));
echo $result; //echoes t****e@example.com
?>
TA贡献1828条经验 获得超3个赞
这是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}`)
这是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];
两者都将您的示例电子邮件变成:
tsa****y@gm***.com
TA贡献1887条经验 获得超5个赞
在PHP中
用正则表达式提取中间部分:
preg_match('\w(?<mid1>.*?)@\w(?<mid2>.*?)\.(?<ext>\w+)', $email, $matches)
替换为字符串长度的 1/3
str_replace($matches['mid1'], str_repeat('*'), strlen($matches['mid1']))
添加回答
举报