phpemailreplacesanitizationredaction

Find and redact an email address in a string


How do I prevent people from presenting their email address in the description field by replacing their email with some words? For example, if a user entered the following text:

Please contact me via joe.joey@email.com.

I want the output to be:

Please contact me via <email address is blocked>.

I know of a basic str_replace() function, but the output would simply be:

//output is Please contact me via joe.joey <email address is blocked> email.com
$string = 'Please contact me via joe.joey@email.com.';
$lookfor = '@'; 
$replacewith = '<email address is blocked>';      
$newstring = str_replace($lookfor, $replacewith, $string);

Solution

  • This is a perfect time to use preg_replace. I've slightly simplified the requirements for a valid email here (emails can be horridly complex), but something like:

    $newstring = preg_replace("/[\w-]+@([\w-]+\.)+[\w-]+/", $replacewith, $string);