0

Consider a php script visited with URL of foo?q=some&s=3&d=new. I wonder if there is a paractical method for parsing the url to create links with new variable (within php page). For example foo?q=**another-word**&s=3&d=new or foo?q=another-word&s=**11**&d=new

I am thinking of catching the requested URL by $_SERVER['REQUEST_URI'] then parsing with regex; but this is not a good idea in practice. There should be a handy way to parse variables attached to the php script. In fact, inverse action of GET method.

Googlebot
  • 15,159
  • 44
  • 133
  • 229
  • For "inverse action of GET method", do you want to propose an HTTP GIVE method? ;o) – deceze Oct 24 '11 at 06:41
  • No I meant something like parse_url but not dealing with the entire url; just only queries. Your idea is quite good; I just thought there might be a more specific function to do so. – Googlebot Oct 24 '11 at 06:53

3 Answers3

5

The $_GET variable contains an already parsed array of the current query string. The array union operator + makes it easy to merge new values into that. http_build_query puts them back together into a query string:

echo 'foo?' . http_build_query(array('q' => 'another-word') + $_GET);

If you need more parsing of the URL to get 'foo', use parse_url on the REQUEST_URI.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

What about using http_build_query? http://php.net/manual/en/function.http-build-query.php

It will allow you to build a query string from an array.

sberry
  • 128,281
  • 18
  • 138
  • 165
1

I'd use parse_str:

$query = 'q=some&s=3&d=new';
parse_str($query, $query_parsed);
$query_parsed['q'] = 'foo-bar';
$new_query = implode('&', array_map(create_function('$k, $v', 
                                   'return $k."=".urlencode($v);'), 
                          array_keys($query_parsed), $query_parsed));
echo $new_query;

Result is:

q=foo-bar&s=3&d=new

Although, this method might look like "the hard way" :)

Nemoden
  • 8,816
  • 6
  • 41
  • 65