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
  • 1
    Graham if someone gave you the answer you are looking for, don't forget to accept that answer so people know the question is resolved. – Blizz May 14 '15 at 10:04
  • 1
    @vivek-mdu I did explain why it's not a duplicate – Greum May 14 '15 at 10:37

2 Answers2

6

You can use:

$email = preg_replace('/(?:^|@).\K|\.[^@]*$(*SKIP)(*F)|.(?=.*?\.)/', '*', $email);

RegEx Demo

This will turn [email protected] into g*****@g*****.com and

[email protected] will become m*******@g*****.co.uk

and [email protected] into t*********@g*****.com

anubhava
  • 761,203
  • 64
  • 569
  • 643
0
^.\K|.(?=.*@)|@.\K|\..*(*SKIP)(*F)|.(?=.*\.)

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

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

vks
  • 67,027
  • 10
  • 91
  • 124