Blog PHP WordPress

automatically convert emails to nospam

To prevent spam comments on one of the sites that I maintain, I send for approval any comment with at least one URL or email address in it. In that way, manual spammers will find no incentive on leaving comments on the site. At the same time, email addresses left by commenters will not be displayed in the site until it is sanitized. However, the amount of comments in the site in question is so many and manually sanitizing comments with emails is becoming a pain.

So I decided to write a hook to filter the comments and auto-convert the emails into NoSpam format. That is, replacing the @(at sign) and . (dot) in the email. So here's the purpose of this auto-conversion.

  1. auto-approve legitimate comments even if it has emails in it

  2. prevent email scrapers from harvesting email addresses left by the commenters

  3. send for manual approval any comment with one or more URL other than emails

Just place the code below anywhere on your template's functions.php.

function Kwatog_NoSpamEmail($text){
$pattern = '/([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*@([a-z0-9])'.'(([a-z0-9-])*([a-z0-9]))+'.'(.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+/i';
preg_match_all($pattern, $text, $emails);
$symbols = array("@", ".");
$safeChars = array("[at]", "[dot]");
foreach ($emails[0] as $email){
$emailsafe = str_replace($symbols, $safeChars, $email);
$text = str_replace($email, $emailsafe, $text);
return $text;

add_filter('pre_comment_content', 'Kwatog_NoSpamEmail');

Here's the sample output after I put in this code.

The code is not actually foolproof but it will be able to trap 90% of the scenarios. Also, the auto-change is applicable for existing and new comments.

I have no intention as of this time to convert snippet into a WordPress plugin so feel free to create one if you feel like it.