Jump to content

Extracting GET variables from a string


NotionCommotion

Recommended Posts

I have a string that looks like /index.php?g1=111&g2=222&g3=333.  How can I obtain the value of g1 (i.e. 111)?  It does not represent the current state of the server thus I cannot just use $_GET.  It also is not necessarily the first item.

The script below appears to work, however, http://php.net/manual/en/function.parse-url.php states
 

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///...) are allowed. For any other scheme this is invalid.

 


It appears that my string is a URI and not a URL, but I might be wrong.

How should this be accomplished

<?php
$str='/index.php?g1=111&g2=222&g3=333';

$array=parse_url($str);
parse_str($array['query'],$get);
echo("<p>{$get['g1']}</p>");
?>
Link to comment
Share on other sites

First use substr to get the query string (whatever is after the ?). Then pass the query string to parse_str

$str='/index.php?g1=111&g2=222&g3=333';

$query_string = substr($str, strpos($str, '?')+1);
parse_str($query_string, $array);

printf('<pre>%s</pre>', print_r($array, 1));
Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.