Obscure email addresses in a sentence

126 Views Asked by At

I am outputting log messages and need to obscure the email addresses in them.

A log message might look like this:

A lead was saved for [email protected], Date: 11th December 2019, Service: Car Hire ( Premium ), Extras: NA, Price: £300

I am using:

preg_replace('/(?<=.).(?=.*?@)|(?<=@.).*(?=\.com)/u', '*', $email);

I am using this regex to obscure emails, which works great when it's just an email, but in a sentence, it does this....

A********************************@example.com, Date: 11th December 2019, Service: Car Hire ( Premium ), Extras: NA, Price: £300

Is there a way to only make it go back as far as the space?

So the required result would be:

A lead was saved for ************@example.com, Date: 11th December 2019, Service: Car Hire ( Premium ), Extras: NA, Price: £300",
1

There are 1 best solutions below

0
On

If the objective is to obscure/obfuscate email addresses, then don't let anyone know how many characters are being converted to asterisks.

Match the substrings before the @ and replace them with a static number of asterisks.

Code: (Demo)

$string = 'A lead was space" ema il "@emailadds.com saved for [email protected], Date: 11th December 2019, Service: Car Hire ( Premium ), Extras: NA, Price: £300';

echo preg_replace('/(?:[^"\s@]+|"[^"]*")+(?=@[^\s.]+\.)/', '******', $string);

Output:

A lead was ******@emailadds.com saved for ******@website.com, Date: 11th December 2019, Service: Car Hire ( Premium ), Extras: NA, Price: £300