Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- Bag-O-Tricks for PHP II


andreasfriedrich - 2:26 pm on Mar 21, 2003 (gmt 0)


Encoding email addresses

While this is certainly not a very safe way to prevent spam bots from picking up your email addresses it works for the time being since those bots are written with speed in mind so they generally do not decode entities before parsing the html code.


$html = preg_replace [php.net](
"'((?:mailto:)?[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z]{2,3})'e",
'encode_email($1)',
$html);
function encode_email($txt) {
$n = strlen [php.net]($txt);
for($i = 0; $i<$n; $i++) {
$a = substr [php.net]($txt, $i, 1);
$new .= sprintf [php.net]('&#%s;', ord($a));
}
return [php.net] $new;
}

The script will look for anything that looks like a mailto: link and convert it into numeric entities. Browsers will decode the link while spam bots will not.

If you retrieve the email address from a db you can call encode_email directly as well. And as always a call back function with ob_start [php.net] will work great for any post processing.

This method should be ok in the EU as well where you are required to put a working and easy to find and use email address on your site. I believe that JavaScript solutions will not suffice since you need JavaScript enabled to view the email address.

Andreas


If you like Perl [perl.com] better there is a Perl [perl.com] version in the Bag-O-Tricks for Perl [webmasterworld.com]


Thread source:: http://www.webmasterworld.com/php/334.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com