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

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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"

2 Comments

Unfortunately it's user input. So user might input an invalid URL like i.imgur.com/YsSs2FK.png&stuff that pulls up in a browser...
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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.