1

This is a follow up on this question Use PHP to Get File Path/Extension from URL string

Given a string which is a URL: http://i.imgur.com/test.png&stuff

How do I get the name of a file: test.png without query parameters?

If I try suggested solution: parse_url($url, PHP_URL_PATH) I get /test.png&stuff

Community
  • 1
  • 1
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

3 Answers3

4

Unfortunately, it's not using a normal URL string, since it doesn't have the ? to separate out the query string. You may want to try using a few different functions together:

$path = parse_url($url, PHP_URL_PATH);
$path = explode('&',$path);
$filename = $path[0]; // and here is your test.png
aynber
  • 22,380
  • 8
  • 50
  • 63
2
parse_url($url, PHP_URL_PATH) I get /test.png&stuff

That's because you're giving it a URL which contains no query string. You meant /text.php?stuff; the query string is defined by an ?, not a &; & is used to append additional variables.

To extract the query string, you want PHP_URL_QUERY, not PHP_URL_PATH.

$x = "http://i.imgur.com/test.png?stuff";

parse_url($x, PHP_URL_QUERY); # "stuff"
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Unfortunately it's user input. So user might input an invalid URL like http://i.imgur.com/YsSs2FK.png&stuff that pulls up in a browser... – dev.e.loper Oct 28 '13 at 20:22
  • 1
    Then tell them their input is invalid. If they're feeding you bad input, you should *tell* them it's bad input, not try to guess at what they meant to type. In the case of your imgur link, the `&stuff` isn't *doing* anything, so you probably don't need to extract anything. – user229044 Oct 28 '13 at 20:23
0

based on @Mark Rushakoff's answer the best solution:

<?php
$path = "http://i.imgur.com/test.png?asd=qwe&stuff#hash";
$vars =strrchr($path, "?"); // ?asd=qwe&stuff#hash
var_dump(preg_replace('/'. preg_quote($vars, '/') . '$/', '', basename($path))); // test.png
?>
  1. Regular Expression to collect everything after the last /
  2. How to get file name from full path with PHP?
eapo
  • 1,053
  • 1
  • 19
  • 40