6

I have found two topics which at first appear to answer my query but they only seem to get me part-way to a solution. Using them I have got to where I am. So it's not a duplicate!

I want to replace all but the first character in the name part and domain part of an email address with an asterisk:

eg

g******@g****.com or g******@g****.co.uk

code:

$email2 = preg_replace('/(?<=.).(?=.*@)/', '*', $email);
$email3 = preg_replace('/(?<=@.)[a-zA-Z0-9-]*(?=(?:[.]|$))/', '*', $email2);

which is almost there but gives me g******@g*.com rather than g******@g*****.com

Can anyone help me with the regex please?

Greum
  • 81
  • 1
  • 5

2 Answers2

6

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

anubhava
  • 713,503
  • 59
  • 514
  • 593
0
^.\K|.(?=.*@)|@.\K|\..*(*SKIP)(*F)|.(?=.*\.)

You can try this.Replace by *.See demo.

https://regex101.com/r/mT0iE7/20

vks
  • 65,133
  • 10
  • 87
  • 119