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: 24,245
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

Some Words on the Sentencing of Barrett Brown

No hero
LGF • Views: 22,248

Barrett Brown, who occasionally posted in our LGF Pages section a few years ago, was sentenced today to 63 months in prison for transmitting threats, being an accessory to hacking charges, and interfering with a search warrant.

There’s already an outcry against this from the libertarian “hacktivist” community, who are trying to paint Brown as a hero of free speech, unfairly imprisoned by the government.

I knew Barrett Brown through phone conversations and email before he got involved with the hacking of Stratfor, and for a while I thought of him as a friend — but man, was I ever wrong.

Long story short, some of the things he posted at LGF were criticized by our commenters and Barrett went absolutely nuts about it, in a classic ultra-narcissist reaction. He blamed me for the criticism (ironically, one of the comments he was most upset about said he was risking getting in trouble with the FBI), and began a secret campaign to hack Little Green Footballs (causing a DDoS attack at one point) and poison my reputation by revealing private emails between him and me to none other than far right anti-Islam blogger Pamela Geller.

Barrett Brown is no hero of free speech. He’s a vindictive, vengeful thug.

I don’t wish ill on Brown, despite the horrible shit he pulled on me. But it makes me sick to see him praised as a free speech icon, when he plotted to out my private information and hack my website. That’s the real Barrett Brown, not the glamorized image his followers are trying to push out there.

UPDATE at 1/22/15 2:21:51 pm by Charles Johnson

Below is a link to a leaked chat log from 2011 in which Barrett Brown discusses his plots against LGF and me personally, spews homophobic, racist and antisemitic slurs, and all kinds of other nastiness.

Related

Guess Who’s Been Arrested Again

America’s favorite responsible gun owner
LGF • Views: 24,526

George Zimmerman is currently in jail in Seminole County Florida on aggravated assault charges, with domestic violence and weapon enhancements. Also, he’s not eligible for bail, which on top of the weapon and domestic violence upgrades is a really bad sign. Edit, Update 1: Zimmerman has now seen the judge and is being held on a $5000 bond.

This picture is difficult to masturbate to.

Update 2: We now have a bit more of the story. Seems Zimmerman lost his temper and the weapon the assault refers to was a bottle of wine.

Judge John Galluzzo gave few details of the incident, but said a wine bottle was involved and that the alleged assault happened at Zimmerman’s home. Prosecutors questioned whether substance abuse treatment was needed, but the judge said that didn’t seem to be a factor.

After the brief hearing, Zimmerman’s attorney, Don West, told the Orlando Sentinel (tinyurl.com) his client was arrested after allegedly throwing a wine bottle at his girlfriend several days ago.

Zimmerman, who wore blue scrubs and handcuffs, appeared calm during the brief hearing. At one point, he laughed and joked with an officer as he signed paperwork.

Although the incident didn’t involve a firearm, the judge ordered Zimmerman to surrender any weapons out of an abundance of caution.

News like this calls for some quality old school Was (Not Was)

Youtube Video

Happy New Year!

An open thread as we start another trip around the Sun
LGF • Views: 32,143

In Times Square they’re preparing to drop the ball, and here’s an open thread to ring in the new year at LGF. I wish all of our readers the very best in 2015!

A Post-Christmas Recovery Open Thread, Featuring HMSTR

Rodent punks
LGF • Views: 20,759

YouTube

You could never fully steal the show when you’re followed by the blown-out spectacle of Sun Ra Arkestra’s Tiny Desk Concert. But the opening act kept jumping on the piano and nibbling on the set, literally pulling up the carpet and leaving “presents” on the floor. How could we not have them back? Did I mention they’re hamsters?

Joni and Nash — first names only, please, like Madonna and Cher — are HMSTR. Certainly not the first band to count rodents among its members, but at least they refuse to release a punk album with no punk to be found. “Snow Day” is HMSTR’s first single, a twee-as-all-get-out holiday pop-punk song by virtue of having “snow” in its title. After what sounds like digital snowflakes, the song unleashes a one-minute snowball fight with the fuzziest Tiny Desk destroyers we’ve ever seen.

You can download “Snow Day” from HMSTR’s Bandcamp page. Happy holidays! — LARS GOTRICH

Our End-of-the-Year Subscription Special: Ad-Free Subscriptions 25% Off!

Go ad-free for less
LGF • Views: 28,499

For this Christmas and New Year we’re offering a special discount on our ad-free subscriptions, that automatically turn off all advertisements at LGF when you’re logged in. For a limited time, one-year ad-free subscriptions are just $59.95 — a savings of 25% off the normal price. An ad-free subscription lets LGF run much faster, since the ads are never loaded by the browser at all. And well, let’s admit it, it looks a lot better too.

(Note: to make the subscription process fully automatic, you should already be signed in to an LGF user account when you click the Subscribe button.)

By special request, we’re also accepting gift subscriptions for LGF members this year, but since our subscriptions are managed by PayPal and they don’t actually support this with their system, we’ll need to set it up manually. So instead of using the Subscribe button to send a gift subscription, use the Donate button (below), make the donation for the subscription price, then in the space provided in the PayPal form for a message, let us know the LGF username the subscription is for, and we’ll set up the account manually for one year of ad-free access.

Note to LGF Pages Contributors: Use More Images!

Your daily browbeat
LGF • Views: 33,844

Here’s a quick note to remind all of our LGF Pages contributors that using images is … good! It’s a good thing! And setting up the LGF Facebook Page has provided us with a great example of why this is so.

Here’s our Facebook page, showing the last four LGF Pages I’ve posted there:

If we scroll down past these posts, here’s what the last three LGF front page articles look like:

Those nice big full-width images! That’s what I’m talking about. If you don’t include an image in your LGF Page we substitute our default green football logo, because Facebook actually requires an image of some kind for these posts. But as you can see, if there are several of these default images in a row it tends to look monotonous and uninviting.

If you post a video clip from YouTube or Vimeo in an LGF Page, a video thumbnail “meta image” will automatically be set up for you by our software. But if you’re not posting a video, it’s up to you to plug in an image of some kind, and I’ve coded things so that’s about as easy as possible by letting you drag and drop images into the editing area of our LGF Pages window to upload them.

Facebook tries to figure out how to crop and clip images; if they won’t fit in that full-width area above the post, it may put them in a smaller left-aligned area. Images below 250 pixels width always seem to go in that area, and that’s where the default green football logo appears.

Remember — you can’t violate copyrights. Don’t grab news photos from the Associated Press or Reuters or those kinds of places. But Google’s image search can often turn up interesting images that aren’t copyrighted, and you can also use screen capture software to grab screenshots when appropriate (which I did to produce the images above).

Pro-tip: if you’re posting about a specific person or thing, uploading a portrait shot and giving it a tag with the name of the person/thing lets you quickly re-use the image by searching for the tag with our Image Library system, the next time you write about that person or thing.

Images aren’t only important on Facebook, by the way; they’re also used for Twitter’s previews (“Twitter Cards”) that show up in tweets about your Page.

Now, none of this is mandatory, of course. You can always post an LGF Page without an image, and we won’t put you in the stocks for it. But if you’d like it to look as nice as possible on these social media sites (where it’s going to end up anyway), images are the cat’s pajamas! Use one today!

Little Green Footballs Now Has an Official Facebook Page With Its Own Address

LGF • Views: 28,032

I’ve been working on this for a while, and tonight I’m proud to launch the official Little Green Footballs Facebook Page, where you’ll find both front page articles and user-submitted LGF Pages featured in their own little corner of Facebook, with its own web address.

New LGF Feature: Download a Copy of Your Entire Image Library

Back it up
LGF • Views: 25,501
Image via Shutterstock

Here’s a brand new feature I’m sure everyone who uses LGF’s personalized Image Library system (available free to registered users) will appreciate: now you can download your entire collection of images in a ZIP file. When you expand the file, it creates a directory structure with all the images neatly filed in folders and subfolders named by dates.

Since these zip archives can be quite large depending on how many images you’ve uploaded, there’s a limit of one archive download per user per week.

Still to do: I haven’t decided yet how to handle tags, captions and other “meta” information about the images. But having a complete backup of all your images is such a useful feature as is, I decided to go live with it now.

It’s simple to use; only one button labeled “Download Image Library,” visible at upper right in the Image Library main page.

^ 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
Here’s how the BBC, disrupted by technology and new habits, is thinking about its future
... but on their interactive page they use Flash. The BBC was first granted a royal charter in 1927, and the charter has been renewed every 10 years since then. Its current charter expires on Dec. 31, 2016, and the ...

1 hour, 20 minutes ago
Views: 69 • Comments: 0
Tweets: 0 • Rating: 0
Mich-again
Tech start-up infuses street view maps with infrared images
Pathteacher: MIT Professor invents way to illegally search thousands of homes for his business start-up. What in the world are these people thinking? The legality of their business model, which involves taking unsolicited drive-by heat scans of private residences is ...

5 hours, 3 minutes ago
Views: 83 • Comments: 0
Tweets: 1 • Rating: 0
Rightwingconspirator
Tighten the Rules on E-Cigarettes? Is This Good Oversight?
The state report is not, however, an objective assessment. It obviously includes only the most damaging information about e-cigarettes. For example, some other studies have found potentially encouraging signs that vaping might help some smokers quit. In other words, ...

1 day ago
Views: 179 • Comments: 3
Tweets: 0 • Rating: 5
FemNaziBitch
Watch a US Senator Cite the Bible to Prove That Humans Aren’t Causing Global Warming
When Whitehouse first introduced this amendment a couple days ago, he made clear that by "climate change," he was referring to "what our carbon pollution...is doing to our atmosphere and what it is doing to our oceans." But the ...

1 day, 7 hours ago
Views: 312 • Comments: 2
Tweets: 0 • Rating: 0
Khal Wimpo
Chuck C. Johnson boosting Twitter via fake followers
...in related news, water found to be wet. It's become common for politicians and companies looking to puff up their social profiles to "buy" followers from shady-ass sploggers. Which works when you're starting up, but after you start to get ...

2 days, 16 hours ago
Views: 690 • Comments: 2
Tweets: 149 • Rating: 6
aagcobb
The Average American Household Was Poorer in 2013 Than It Was in 1983 - Vox
Matthew Yglesias, Vox: The Average American Household Was Poorer in 2013 Than It Was in 1983 - Vox US net worth rose considerably over that period, which is what you would expect to see. Technology has improved and productivity increased, ...

2 days, 17 hours ago
Views: 232 • Comments: 0
Tweets: 0 • Rating: 4
Lumberhead
Scott Walker’s Divisive Message
If any candidate could run a rigid campaign of polarization--aimed at winning as many white voters as possible--it's Walker. His language is already there. In his Iowa speech, he touted voter-identification laws and portrayed disadvantage as a pure product ...

2 days, 17 hours ago
Views: 382 • Comments: 1
Tweets: 5 • Rating: 4
Rocky-in-Connecticut
Republican Governor’s State-Run Media Outlet
I guess Republicans are against state-run enterprises except when they are for it. Indiana Governor (R) to start up State-Run official mouthpiece news outlet.indystar.com Hey- If a nice guy Republican/Tea Party favorite like Putin can have his own state-run mouthpiece, ...

2 days, 23 hours ago
Views: 257 • Comments: 1
Tweets: 0 • Rating: 4
The Vicious Babushka
What a Soviet Soldier Saw When His Unit Liberated Auschwitz 70 Years Ago
More: What a Soviet Soldier Saw When His Unit Liberated Auschwitz 70 Years Ago When the Soviet Army's 322nd Rifle Division entered the concentration camp at Auschwitz on Jan. 27, 1945, they found a desolation. Mounted on shaggy ponies, they ...

4 days, 3 hours ago
Views: 653 • Comments: 5
Tweets: 3 • Rating: 9
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 ...

1 week, 5 days ago
Views: 679 • Comments: 2
Tweets: 2 • Rating: 6
 Frank says:

I figure the odds are fifty-fifty I just might have some thing to say.