I am new to regex and I am trying to substitute some characters for asterisk in php like below:
email: victor@gmail.com -> v****r@g***l.com
I have done this:
$email = preg_replace('/(?:^|@).\K|\.[^@]*$(*SKIP)(*F)|.(?=.*?\.)/', '*', $linha['cli_email']);
The problem is that the output is v*****@g****.com instead of v****r@g***l.com and I don't know how to show the last for the username and last for the email provider.
You can try this:
$email = preg_replace('/(?:^|.@).\K|.\.[^@]*$(*SKIP)(*F)|.(?=.*?\.)/', '*', $linha['cli_email']);
Hope it helped..
Here first of all we are matching string using regex.
Regex: (?<=\b[a-z])[a-zA-Z0-9]+(?=.\@)|(?<=@.)[a-zA-Z0-9]+(?=.\.)
(?<=\b[a-z])[a-zA-Z0-9]+(?=.\@)says match characters positive looking ahead forone characterand@and positive looking backward forboundary conditionanda character.
(?<=@.)[a-zA-Z0-9]+(?=.\.)says match characters positive looking ahead forone characterand.and positive looking backward for@condition and a character.
<?php
ini_set('display_errors', 1);
$email="victor@gmail.com";
preg_match_all('/(?<=\b[a-z])[a-z]+(?=.\@)|(?<=@.)[a-z]+(?=.\.)/',$email,$matches);
foreach($matches[0] as $key => $value)
{
$email=str_replace($value, getStars(strlen($value)), $email);
}
echo $email;
function getStars($length)
{
$string="";
for($x=0;$x<$length;$x++)
{
$string.="*";
}
return $string;
}
You need to be accounting for all types of email address. How will the accepted answer handle email addresses like m@example.com or user@host.example.com or or joe@m.com?
<?php
function starmid($str) {
switch (strlen($str)) {
case 0: return false;
case 1: return $str;
case 2: return $str[0] . "*";
default: return $str[0] . str_repeat("*", strlen($str) - 2) . substr($str, -1);
}
}
function hideemail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
list($u, $d) = explode("@", $email);
$d = explode(".", $d);
$tld = array_pop($d);
$d = implode(".", $d);
return starmid($u) . "@" . starmid($d) . ".$tld";
}
$emails = [
"victor@gmail.com",
"v@example.com",
"victor@g.com",
"victor@host.example.com",
"victor+foo@gmail.com",
"invalid@",
];
foreach ($emails as $email) {
echo hideemail($email) . "\n";
}