Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially hiding an email address with PHP regex [duplicate]

Tags:

regex

php

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?

like image 542
Greum Avatar asked May 14 '15 09:05

Greum


1 Answers

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

like image 190
anubhava Avatar answered Oct 16 '22 16:10

anubhava