Quick and easy email encoding view helper

Last modified date

Comments: 0

Here’s a quick and easy view helper for Zend Framework that will encode an email address. It will encode just an email address or return a whole mailto link. The encoding is basically the same as in the Smarty template engine.

Obviously there’s a lot of room for improvement; javascript encoding, representation as an image, and so on… but then it wouldn’t be quick an easy – it’d be slightly longer and just a little more complex. 😉


[code language=”php”]
class Amnuts_View_Helper_EncodeEmail extends Zend_View_Helper_Abstract
{
/**
* Return the class on direct calls.
*
* @return Amnuts_View_Helper_EncodeEmail
*/
public function encodeEmail()
{
return $this;
}

/**
* Return an encoded email address to help against spam.
*
* @param string $address The email address to encode
* @return string
*/
public function address($address)
{
$xhtml = ”;
$address = (string)$address;
$len = strlen($address);
for ($x = 0; $x < $len; $x++) {
if (preg_match(‘!\w!’, $address[$x])) {
$xhtml .= ‘%’ . bin2hex($address[$x]);
} else {
$xhtml .= $address[$x];
}
}
return $xhtml;
}

/**
* Return an encoded mailto link to help against spam.
*
* If no link text is supplied then the email address will be used
* (as is generally preferred).
*
* @param string $address The email address to encode
* @param null|string $text Text to use for link
* @param array $attrs Any extra attributes for link
* @return string
*/
public function link($address, $text = null, array $attrs = array())
{
$encodedtext = ”;
$encodedaddress = $this->address($address);
if (null === $text) {
$text = (string)$address;
} else {
$text = (string)$text;
}
$len = strlen($text);
for ($x = 0; $x < $len; $x++) {
$encodedtext .= ‘&#x’ . bin2hex($text[$x]).’;’;
}
$xhtml = ‘<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;’ . $encodedaddress . ‘"’;
if (!empty($attrs)) {
foreach ($attrs as $k => $v) {
$xhtml .= ‘ ‘ . $this->view->escape($k) . ‘="’ . $this->view->escape($v) . ‘"’;
}
}
$xhtml .= ‘>’ . $encodedtext . ”;
return $xhtml;
}
}
[/code]

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.