问题
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?
回答1:
Take the last component of the path and remove any extension on it.
One approach:
$id = pathinfo($url, PATHINFO_FILENAME);
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/27003793/get-the-id-of-an-imgur-image