Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Encode email addresses in content text


Reply


3 Posts   510 Views

Avatar
teel

Community Member, 5 Posts

9 February 2013 at 2:41am

Hi,

How should I encode email addresses in content text in my templates so that spam bots won't recognize them? I've tried a couple of modules, but they either throw errors or do nothing and all and none of them have any kind of documentation about how to use them.

Avatar
Willr

Forum Moderator, 5513 Posts

9 February 2013 at 3:14pm

So you have email addresses embedded within a text field? Email::obfuscate() handles encoding email addresses to 'hide' the addresses but this only works on a single email (it won't replace all email addresses within content).

I'd do something like.. (not tested, but should give you a start)

function getEmailEscapedContent() {
$content = $this->Content;
$callback = function($matches) {
Email::obfuscate($matches[0]);
};

return DBField::create_field('HTMLText', preg_replace_callback("/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i", $callback,$content));
}

Then instead of using $Content to output, use $EmailEscapedContent

Avatar
teel

Community Member, 5 Posts

12 February 2013 at 12:11am

Edited: 12/02/2013 12:13am

Thanks, that works (after I added 'return' to the callback, in case some else ever tries this :).

edit:

I ended up putting this code in my PageController, so I can escape any field, not just content

function EscapeEmail($content) {
$callback = function($matches) {
return Email::obfuscate( $matches[0], 'hex' );
};

return DBField::create_field( 'HTMLText', preg_replace_callback( "/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i", $callback, $content ) );
}

And in template:

$EscapeEmail($Content)