I have a simple task to do with PHP, but since I\'m not familiar with Regular Expression or something... I have no clue what I\'m going to do.
what I want is very si
You'll need a specific function for each. For mails:
function hide_mail($email) {
$mail_segments = explode("@", $email);
$mail_segments[0] = str_repeat("*", strlen($mail_segments[0]));
return implode("@", $mail_segments);
}
echo hide_mail("example@gmail.com");
For phone numbers
function hide_phone($phone) {
return substr($phone, 0, -4) . "****";
}
echo hide_phone("1234567890");
And see? Not a single regular expression used. These functions don't check for validity though. You'll need to determine what kind of string is what, and call the appropriate function.
I tried for a single-regex solution but don't think it's possible due to the variable-length asterisks. Perhaps something like this:
function anonymiseString($str)
{
if(is_numeric($str))
{
$str = preg_replace('/^(\d*?)\d{4}$/', '$1****');
}
elseif(($until = strpos($str, '@')) !== false)
{
$str = str_repeat('*', $until) . substr($str, $until + 1);
}
return $str;
}
I create one function to do this, works fine for me. i hope help.
function ofuscaEmail($email, $domain_ = false){
$seg = explode('@', $email);
$user = '';
$domain = '';
if (strlen($seg[0]) > 3) {
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0].$sub_seg[1];
for ($i=2; $i < count($sub_seg)-1; $i++) {
if ($sub_seg[$i] == '.') {
$user .= '.';
}else if($sub_seg[$i] == '_'){
$user .= '_';
}else{
$user .= '*';
}
}
$user .= $sub_seg[count($sub_seg)-1];
}else{
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0];
for ($i=1; $i < count($sub_seg); $i++) {
$user .= ($sub_seg[$i] == '.') ? '.' : '*';
}
}
$sub_seg2 = str_split($seg[1]);
$domain .= $sub_seg2[0];
for ($i=1; $i < count($sub_seg2)-2; $i++) {
$domain .= ($sub_seg2[$i] == '.') ? '.' : '*';
}
$domain .= $sub_seg2[count($sub_seg2)-2].$sub_seg2[count($sub_seg2)-1];
return ($domain_ == false) ? $user.'@'.$seg[1] : $user.'@'.$domain ;
}
For e-mails, this function preserves first letter:
function hideEmail($email)
{
$parts = explode('@', $email);
return substr($parts[0], 0, min(1, strlen($parts[0])-1)) . str_repeat('*', max(1, strlen($parts[0]) - 1)) . '@' . $parts[1];
}
hideEmail('hello@domain.com'); // h****@domain.com
hideEmail('hi@domain.com'); // h*@domain.com
hideEmail('h@domain.com'); // *@domain.com