I'm reading up on pathinfo
basename
and the like. But all I am gathering from those are how to obtain the details I want when using an absolute/relative path. What I am trying to figure out is how can I get the filename.ext
from a url string (not necessarily the active URL, maybe a user input url).
Currently I am looking to get the file name and extension of user provided URLs containing images. But may want to extend this further down the road. So in all I would like to figure out how I can get the filename and extension
I thought about trying to use some preg_match
logic finding the last / in the url, spliting it, finding the ? from that (if any) and removing the point beyond that and then trying to sort it out after with whats left. but I get stuck in cases where the file has multiple .
in the name ie: 2012.01.01-name.jpg
So I am looking for a sane optimal way of doing this without to much margin of error.
$path = parse_url($url, PHP_URL_PATH); // get path from url
$extension = pathinfo($path, PATHINFO_EXTENSION); // get ext from path
$filename = pathinfo($path, PATHINFO_FILENAME); // get name from path
Also possible with one-liners:
$extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
$filename = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With