Get the ID of an imgur image

7.8k views Asked by At

Here are some examples of imgur links:

https://imgur.com/gallery/s2Bqq
https://i.imgur.com/26xcQUF.jpg
http://i.imgur.com/rfw7jrU.gif
http://i.imgur.com/rfw7jrU.gifv

The imgur API specifically asks for the ID of the image (s2Bqq, 26xcQUF, etc), but offers no way, from what I've seen, to get the ID of an image given a link.

So my question is, how would I, using PHP, get the ID of any imgur link?

3

There are 3 answers

0
AudioBubble On BEST ANSWER

Take the last component of the path and remove any extension on it.

One approach:

$id = pathinfo($url, PATHINFO_FILENAME);
1
dynamic On

With parse_url() you can obtain all your information:

print_r(parse_url('https://i.imgur.com/26xcQUF.jpg'));

Array
(
    [scheme] => https
    [host] => i.imgur.com
    [path] => /26xcQUF.jpg
)

In this case just do:

echo substr( $array['path'],1,-4);

Live: http://ideone.com/0N6cmj

0
arcyqwerty On

This could possibly be done using regular expressions

A simple example would be ^.+/([^/]+)(\.[^/]+)?$ which matches the last part of the url, minus any extension present.

To use it in PHP, preg_match('#^.+/([^/]+)(\.[^/]+)?$#', $url, $matches) and $matches[1] will have the id.