Thursday, November 11, 2010

autolinking images in rich email

So if you have ever done rich email design, you know that it can be a good idea to link every image in the email to a URL in order to increase clicks, but if you have a giant, sliced up design with tons of individual images, it's a pain to assign a link to each one. When I get a case like this, I don't link any of the images (unless they are going to very specific subpages) Instead I let a server script process the page and assign every non-linked image a master link.

Now we don't want to over write existing linked images, so there also has to be a way to leave those alone and just link the "naked" images. Probably could use a little more polish, but here is the basic idea


(PHP)

function autolink($file, $link){
// autolink function
// This function will apply a master link to all images in a page
// provided they are not linked already -- which can be handy for email blasts to get more clicks
// NOTE: if there are any characters, including whitespace
// between the opening A tag and the IMG tag (found in poor HTML), that A tag will
// not be excluded from the main pattern, therefore any enclosed images
// that meet this condition will end up with nested A tags (for the IMG) and the IMG will be linked to the master link.
// however this should not break most browsers if it happens
// for best results, this function should be combined with the noimgborders function
// also available in the hankpants library.

// find all EXISTING linked images and transcode
// them into html entities to hide them from the main REGEX pattern
// (swap these back in later)
$link = trim($link);
$i=0;
$_ = preg_match_all('/\<a\s[^\>]+?\>\<img.+?\>\<\/a>/ism', $file, $alreadylinked);
foreach($alreadylinked[0] as $hello){
$world[$i] = htmlentities($hello);
$file = str_replace ($hello, $world[$i], $file);
$i++;
}
// existing linked images now escaped, run our main link replacement REGEX
$i=0;
$file = preg_replace('/\<img.+?\>/ism', '<a href="'.$link.'">$0</a>', $file);
// swap back in the linked images that were hidden by transcoding
foreach($world as $hello){
$decodelink = html_entity_decode($hello);
$file = str_replace ($hello, $decodelink, $file);
}
return $file;
}

No comments: