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
https://forums.phpfreaks.com/topic/293895-extracting-get-variables-from-a-string/
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));

or

<?php
     $str = "/index.php?g1=111&g2=222&g3=333";
     $bits = parse_url($str);
     parse_str($bits['query'], $vals);
     echo '<pre>',print_r($vals, true),'</pre>';
?>

gives

Array
(
    [g1] => 111
    [g2] => 222
    [g3] => 333
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.