2

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 sharon.davis@example.com, 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",
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Collins
  • 1,069
  • 14
  • 35

1 Answers1

0

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 sharon.davis@website.com, 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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136