TwitterFacebook

Tech Note: A Regular Expression to Extract the ASIN Product Code From Any Amazon URL

So much fun it must be ASIN
LGF • Views: 4,496
Image via Shutterstock

Every once in a while I come up with a bit of code that might be useful to other programmers, and here’s one of those bits — a regular expression that extracts the ASIN product code from almost any Amazon product URL, including URLs from non-US Amazon stores. (It doesn’t handle pages of search results or other index pages, however.)

I use this at LGF to rewrite links to Amazon and add our affiliate ID to the link, so if someone clicks the link we get a small percentage of the purchase price when they buy something.

This code used to be a series of regular expressions that matched each type of URL, but I was looking at it this week and realized it might be possible to condense the whole process down to just one regex. And after extensive testing, I think I may have gotten pretty close to a universal Amazon ASIN extractor. (I searched Google, and couldn’t find anything this good online.)

In this PHP code, I used the x modifier to let me split the regex across multiple lines with comments and indenting. I also used ~ for the regular expression delimiter so all the forward slashes don’t need to be escaped. These two steps make the code much more readable, but if you use this regex with a language that doesn’t allow you to change the delimiter you’ll need to insert a backslash before each forward slash.

(Notice that I used non-capturing groups for everything except the ASIN product ID.)

<?php
$regex = '~
	(?:www\.)?				# optionally starts with www.
	ama?zo?n\.				# also allow shortened amzn.com URLs
	(?:
		com					# match all Amazon domains
		|
		ca
		|
		co\.uk
		|
		co\.jp
		|
		de
		|
		fr
	)
	/
	(?:						# here comes the stuff before the ASIN
		exec/obidos/ASIN/	# the possible components of a URL
		|
		o/
		|
		gp/product/
		|
		(?:					# the dp/ format may contain a title
			(?:[^"\'/]*)/	# anything but a slash or quote
		)?					# optional
		dp/
		|					# if short format, nothing before ASIN
	)
	(B[A-Z0-9]{9})			# capture group $1 contains the ASIN
	(?:						# everything after the ASIN
		(?:/|\?|\#)			# beginning with /, ? or #
		(?:[^"\'\s]*)		# everything up to quote or white space
	)?						# optional
~isx';
?>

Here’s a bit of code that puts this regex to work and inserts our affiliate ID into the reconstructed link:

<?php
$text = preg_replace($regex, 'www.amazon.com/dp/$1/?tag=littlegreenfo-20', $text);
?>

And here’s what this regular expression looks like when condensed down to one gnarly line:

<?php
$regex = '~(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?~isx';
?>

If you run this regular expression against the following URL:

http://www.amazon.com/Man-High-Castle/dp/B00RSGFRY8/ref=sr_1_1?s=instant-video&ie=UTF8&qid=1421879835&sr=1-1&keywords=the%20man%20in%20the%20high%20castle

You end up with this:

http://www.amazon.com/dp/B00RSGFRY8/?tag=littlegreenfo-20

Sunday Jam: Neil Finn Live, ‘Fall at Your Feet’

With the original Crowded House band
Music • Views: 4,311

YouTube

Here’s a great live performance by Neil Finn, with the late Paul Hester on drums, doing one of his classic songs, “Fall At Your Feet.”

Neil Finn performing live at the Chapel in support of his One Nil release. Special appearances by Jim Moginie, Paul Hester, and Nick Seymour

Chuck C. Johnson Attacks Dana Loesch: All Sane People Win

“I’m limited legally in what I can reveal.”
Wingnuts • Views: 12,225

Here it is, folks — the hit piece on Dana Loesch Chuck C. Johnson has been threatening to post all day; he finally worked up the guts to go through with it: BUSTED: The Real Dana Loesch: A Hypocrite and a Fraud Lying About Andrew Breitbart and Me.

Hilariously, this whole brouhaha was started when Chuck and Dana got in a pissing match over who was really the inheritor of dead Andrew Breitbart’s “legacy.”

Yes, that’s right — they’re squabbling over who’s the sleaziest bottom feeder of them all. Pardon me while I put on some more popcorn. Can they both win?

UPDATE at 1/24/15 8:22:09 pm by Charles Johnson

Loesch fires back at the Ginger Avenger.

Sarah Palin’s Bizarre Disconnected Word Salad at the Iowa Freedom Freakout, Complete

Palin delivers an entire speech in one incredibly long run-on sentence
Wingnuts • Views: 15,207

YouTube

Even by Sarah Palin’s already low standards, this speech is extraordinarily incoherent and scattered. I’ve seen a lot of her speeches (do not pity me, it is my job), and I can’t remember a more garbled, deeply weird performance from Caribou Barbie.

And Now, Sarah Palin LIVE!

Wingnuts • Views: 11,032

Video

And now, ladies and gentlemen, Caribou Barbie is about to take the stage at the Iowa Freedom Freakout. Let’s give her a warm welcome, shall we?

Bobby Jindal, Anti-Gay Hate Groups, and Religious Right Wackos Hold Prayer Rally in Louisiana

Featuring a televangelist who claims she can raise people from the dead
Wingnuts • Views: 11,521

MSNBC

Creationist Gov. Booby Jindal is hosting a prayer rally in Louisiana today, co-sponsored by the homophobic hate group known as the American Family Association. Yes, that’s loony Bryan Fischer’s gang of religious right wackos. Jindal is trying to stake out a position as the most fanatical far right Christian in the 2016 race, apparently, but he’s got a lot of competition for that slot.

This Rachel Maddow segment does a good job of showing how completely batshit nuts the AFA is.

Amazon Prime Memberships Only $72 (today only)

Great Deals • Views: 12,114

Amazon is promoting their original series Transparent by offering a discount on Prime memberships - today only until midnight PT. Also Transparent is free to watch today.

Amazon Prime

Existing members can (allegedly) buy a one-year membership at this sale price by doing the following (I haven’t tried this, so no guarantees):

  1. Buy a gift membership and send it to yourself.
  2. Turn off auto-renew on your Prime membership.
  3. Use the gift membership to renew your Prime when the time comes.

Sarah Palin Poses With Another Right Wing “Target Sign” Poster

They never learn
Wingnuts • Views: 16,730

Tonight’s Sarah Palin moment features Caribou Barbie obviously approving of a wingnut sign that puts target signs in the Os of Michael Moore’s name.

I’m not Moore’s biggest fan, but hey — shouldn’t Sarah be careful about stuff like this with her blood-stained history of using target signs for political incitement?

Related

^ back to top ^

TwitterFacebook

Turn off all ads for a full year by subscribing!
Take advantage of our New Year subscription special, and save 25% off the normal subscription price! For a limited time, one-year ad-free subscriptions are just $59.95. Turn off all ads for a full year by subscribing now and save!
Read more...

► LGF Headlines

  • Loading...

► Tweeted Articles

  • Loading...

► Tweeted Pages

  • Loading...

► Top 10 Comments

  • Loading...

► Bottom Comments

  • Loading...

► Recent Comments

  • Loading...

► Tools/Info

► Tag Cloud

► Contact

You must have Javascript enabled to use the contact form.
Your email:

Subject:

Message:


Messages may be published unless you request otherwise.
Tech Note:
Using the Contact Form
LGF Pages

This button leads to the main index of LGF Pages, our user-submitted articles. You can post your own LGF Pages simply by registering a free account with us.

Create a Page

This is the LGF Pages posting bookmarklet. To use it, drag this button to your browser's bookmark bar, and title it 'LGF Pages' (or whatever you like). Then browse to a site you want to post, select some text on the page to use for a quote, click the bookmarklet, and the Pages posting window will appear with the title, text, and any embedded video or audio files already filled in, ready to go.

Or... you can just click this button to open the Pages posting window right away.

Last updated: 2014-12-15 2:06 pm PST

LGF User's Guide
Recent Pages
Thanos
Google Web Toolkit Dumps Compatibility for Sake of Upgrades
Google Web Toolkit (GWT), which lets developers build browser-based applications in Java and deploy them in JavaScript, is on track for major enhancements this year. The GWT road map calls for two upcoming upgrades, but the latter will break ...

2 minutes ago
Views: 27 • Comments: 0
Tweets: 0 • Rating: 0
Rightwingconspirator
Open Carry Rifles & Cop Watching-Most Dangerous Convergence This Week
Watkins, a bartender by day, is the coordinator for Open Carry Tarrant County, a hybrid of the cop-watching and open carry movements. The small band of gun-toting Texans warns motorists of DUI checkpoints and speed traps. They also show ...

3 days, 14 hours ago
Views: 575 • Comments: 1
Tweets: 0 • Rating: 2
Ace-o-aces
Charles C. Johnson Is Still Looking for Investors.
4 days, 15 hours ago
Views: 707 • Comments: 7
Tweets: 9 • Rating: 8
FemNaziBitch
PEDESTAL ELITES: Why Women Supporting Rapist Friendly Judges Are the Scariest of All Americans
Why Republican women supporting rapist friendly judges are the scariest of all Americans Posted on May 20, 2014 by bonnie russell I always vote, and don't engage with those who don't. Also, my vote leans to issues, not a ...

5 days, 20 hours ago
Views: 728 • Comments: 0
Tweets: 0 • Rating: 3
Rocky-in-Connecticut
Sports Hero Gang Sign Shame
you know those professional athlete thugs- always flashing gang signs along with his baby mama. Fine example these two are. I expect Fox News and right wing blogs to have this as their cover story pronto. instagram.com Or maybe not. ...

6 days, 11 hours ago
Views: 518 • Comments: 0
Tweets: 0 • Rating: 1
Skip Intro
Republican Net Neutrality Bill Would Gut FCC’s Authority Over Broadband
The party of pure evil strikes again. Net neutrality legislation unveiled by Republicans today would gut the ability of the Federal Communications Commission to regulate the broadband industry. As expected, the bill forbids the FCC from reclassifying broadband as a ...

6 days, 19 hours ago
Views: 475 • Comments: 2
Tweets: 2 • Rating: 5
The Vicious Babushka
Wingnuts Spend MLK Day Spewing Racism & Lies
The usual [wingnut]HURR HURR MLK WAS A REPUBLICAN & ALL TEH DEMOCRATS IS TEH RACIST LIKE THERE HERO ROBERT BYRD!!!! LBJ SAID TEH N WORD!!! HURR HURR[/wingnut] #tcot MLK Day

6 days, 23 hours ago
Views: 941 • Comments: 1
Tweets: 74 • Rating: 4
Michael McBacon
Praise - Marvin Gaye
I've been on a Marvin Gaye kick lately and thought I'd post this song. Enjoy.

1 week ago
Views: 514 • Comments: 2
Tweets: 0 • Rating: 2
John Vreeland
John McAfee: ‘I know who hacked Sony Pictures - and it wasn’t North Korea’
"I can guarantee they are wrong. It has to do with a group of hackers - I will not name them - who are civil libertarians and who hate the confinement the restrictions the music industry and the movie ...

1 week ago
Views: 850 • Comments: 3
Tweets: 0 • Rating: 3
Lumberhead
Shopping While Black: The Role of Race in Retail
The researchers asked the subjects a series of questions about certain behaviors they had encountered while shopping or advertisements they had noticed, and broke out the results by race. They found that across the board, non-white Americans--and especially black ...

1 week, 1 day ago
Views: 723 • Comments: 8
Tweets: 1 • Rating: 4
 Frank says:

I can't think of anything I like more than audience participation -- From the Mothers of Prevention