Rewrite Amazon product links using jQuery, RegEx and PHP

Over at Gamers With Jobs we wanted to rewrite any outbound Amazon product links so that they include the GWJ affiliate ID (every little bit counts when you're a community site). Deciphering Amazon's generally bloated URLs can be tricky, as can knowing what exactly is required when building a link to a product page. So, I cobbled together a couple different pieces of info into a pretty simple solution that I thought I'd share.

First, we wanted a redirect page that would allow us to get metrics on how many product links are followed on our end. This was super-easy to implement in PHP, thanks to a script from Blogthority.

$asin = htmlspecialchars($_GET['asin']);
if ($asin) {
$link = "" . $asin . "?tag=your-affiliate-id-here";

The trickier part was getting any pre-existing Amazon links, along with any links that users don't enter in the local redirect format, to be rewritten. A bit of jQuery and a JavaScript regular expression, inspired by a post over on MusicBrainz, made a quick solution.

Note: If you're using the latest jQuery, you'll want to drop the @ symbol from the initial selector.

$('a[ @href *= "" ]').each(function() {
var href = $(this).attr('href');
var re = /\/([A-Z0-9]{10})(\/|\?|\b)/i
var asin = re.exec(href);
if (asin[1]) {
var shorturl = '/go/amazon?asin='+asin[1];
$(this).attr('href', shorturl);

The script grabs any links with "" in the URL and rewrites them to follow our redirect page using the 10 digit ASIN that it pulls using a regular expression. That's it!