0

Assuming I have the following URL on a webpage, how I can I utilize the explode() function to give me only the ID, and not the rest of the URL that follows the ID?

file.php?id=12345&foo=bar

I can get the ID, but there's always the following "&foo=bar".

Thanks.

2
  • If it's a current request - then just $_GET['id'] Commented Apr 15, 2013 at 22:56
  • No, I need to use explode() (or something similar). I'm lifting the URL directly from the webpage using cURL. Commented Apr 15, 2013 at 22:57

3 Answers 3

5

If you need to treat a valid URL, you can use

parse_url

parse_url documentation

to explode the URL into different part (SCHEME, HOST, PORT, USER...)

and then, use

parse_str

parse_str documentation

on the QUERY part, in order to retrieve an array containing all your parameters. Then, you can catch what you need.

Sign up to request clarification or add additional context in comments.

1 Comment

An important note about parse_url from the manual: "This function doesn't work with relative URLs."
3
parse_str($_SERVER['QUERY_STRING']);
echo $id;

parse_str will create PHP-variables from query-string variables. http://www.php.net/manual/en/function.parse-str.php

Comments

2

If it's a full URL, you can use parse_url() to get the query string part.

If it's just a fragment, you can use explode() to get it, then parse_str():

list($path, $qs) = explode('?', $url, 2);
parse_str($qs, $args);
echo $args['id'];

The 2 tells explode() to break the string into a maximum of 2 parts (before and after the ?, in this case).

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.