HTML Email Address Obfuscation (PHP)
Small class, intended to be used as a callback for preg_replace_callback to obfuscate email addresses. You can also simply pass a string in rather than being obliged to use preg_replace_callback
Supports a number of obfuscation modes
-
part - e.g. test@
-
full - e.g.
- none - e.g. test@example.com
- htmlencode - Generates a javascript snippet to write the address in
document.write('test');
document.write('@');
document.write('example.com');
Although it's targetted with HTML output in mind, it can just as easily be used on plain text
Details
- Language: PHP
- License: GNU GPL V2
Snippet
class EmailObfusCallback {
/** Constructor
*
* @arg obfustype - one of "part","full","none","htmlencode"
* @return void
*/
function __construct($obfustype="full"){
$this->obfustype = $obfustype;
}
/** Function to obscure email addresses in a HTML page
* Intended to be callaed from preg_replace_callback
*
* @arg str - the regex match
* @return str
*/
function obscureEmail($match){
global $conf;
$parts = explode('@',$match[0]);
switch (strtolower($this->obfustype)){
case 'part':
$str = "{$parts[0]}@<Domain Hidden>";
break;
case 'full':
$str = "<Email Hidden>";
break;
case 'none':
$str = $match[0];
break;
default:
$u = '';
for ($i = 0; $i < strlen($parts[0]); $i++){
$u .= '&#' . ord($parts[0][$i]) . ';';
}
$d = '';
for ($i = 0; $i < strlen($parts[1]); $i++){
$d .= '&#' . ord($parts[1][$i]) . ';';
}
$str = "<script type='text/javascript'>\n".
"document.write('$u');\n" .
"document.write('@');\n\n" .
"document.write('$d');" .
"</script>";
}
return $str;
}
}
Usage Example
$str = "Email me at test@example.com for more info";
$callback = new EmailObfusCallback('part');
$regex = "/(([A-Z0-9._%-\+]+)@([A-Z0-9_%-]+)\.([A-Z\.]{2,20}))/i";
echo preg_replace_callback($regex,array($callback, 'obscureEmail'),$str) . "\n";
$callback = new EmailObfusCallback('full');
echo preg_replace_callback($regex,array($callback, 'obscureEmail'),$str) . "\n";
$callback = new EmailObfusCallback('none');
echo preg_replace_callback($regex,array($callback, 'obscureEmail'),$str) . "\n";
$callback = new EmailObfusCallback('htmlencode');
echo preg_replace_callback($regex,array($callback, 'obscureEmail'),$str) . "\n";