In one of my previews posts, I’ve showed how to obfuscate and email with the help of CSS and a bit of Javascript. However, that obfuscation needs the mail address written from right to left.

To make it easy, I’ve code an helper function in PHP (but you could implement in your preferred language) that converts ordinary email to the RTL obfuscation pattern:

<?php
function mail_obfuscation($email) {
  $html = '<a href="#" onclick="this.href=\'mailto:\'+ this.innerHTML.split(\'\').reverse().join(\'\')" style="unicode-bidi:bidi-override;direction:rtl">';
  $html .= strrev($email);
  $html .= "</a>&#x200E;";
  return $html;
}

It is really simple to understand. The only “magic” is made by strrev that changes the direction of the string.

Apply it to text paragraphs

The above function is useful if you need to write the mail alone. But what happen if the mail is inside a text paragraph? We can use the PHP preg_replace_callback function to replace all the mails with the obfuscation code:

<?php
function mail2link($text) {
  $res = preg_replace_callback(
      "/([\w\d\._\+\-]+@([a-zA-Z_\-\.]+)\.[a-zA-Z]{2,6})/",
      create_function(
          '$matches', 'return mail_obfuscation($matches[0]);'
      ), $text);
  return $res;
}

I’ve used a simple regular expression to match the emails, but you can use your favorite regexp (even Django one).