25

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?

4
  • 4
    possible duplicate of Regular expression to parse query string Commented Jan 24, 2011 at 16:23
  • Indeed, a duplicate, however the parse_url solution leads to a new problem, look at my comment to user576875 below. Commented Jan 24, 2011 at 16:28
  • 1
    you could extract the string starting from ? with strstr or explode something and then pass that to parse_str Commented Jan 24, 2011 at 16:40
  • It looks like I can use strstr, thanks Gordon Commented Jan 24, 2011 at 16:58

3 Answers 3

66

You can use parse_url and parse_str like this:

$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];

parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.

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

4 Comments

It seems like parse_url throws a PHP error when using certain URLs, check out this comment on php.net: php.net/manual/en/function.parse-url.php#96433
Yes, it seems it doesn't work on URLs without a host component. This will work with valid HTTP-like URLs.
So, is there any other way to do this?
it don't need the host in URL, just question mark (?) and parameters, $query = parse_url('?test=123&random=abc', PHP_URL_QUERY);
2

I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:

$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);

2 Comments

just out of curiosity, but how come your system doesn't support a native PHP function?
@Vallentin - parse_str() was introduced in PHP 4... maybe (but it is much improbabile) he had a earlier version of PHP
1

the hostname is optional but is required at least the question mark at the begin of parameter string:

$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;

parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );

print_r ( $params );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.