Edhen
Edhen

Reputation: 345

PHP Query String Manipulation

I have a small issue with manipulating the current URL query string to add an extra parameter at the end.

Per example, say there's a category layout for products, the URL would be:

index.php?category=3&type=5

Now, on that page I have a link for a layout that is either a table or a grid. In those URLs I currently have:

<a href="index.php?<?php echo preg_replace($array,'',$_SERVER['QUERY_STRING']); ?>&layout=grid" ...

Then, I do the same for the table href as well. Also in my array I have just:

$array = array ( '/&layout=table/', '/&layout=grid/' )

Is this the right way, or is there a better way for doing this? I'm asking because without preg_replace, it will continue adding that same layout parameter everytime it is clicked, so it will also show the previous parameter, then the next, then the next.. without removing the previous layout parameters.

Any insight on this will be much appreciated.

EDIT: Thanks to the answers below, I have created a little function:

function buildQuery($key,$value) {
$params = $_GET;
$params[$key] = $value;

return http_build_query($params);
}

Then its only a matter off:

<a href="index.php?<?php echo buildQuery('layout','grid'); ?>">grid</a>

this might seem pointless but i like to have my view / template files without the extra set vars. Im a clean freak. I might even return the 'index.php?' with it just so i can be more lazy, anyways something to play with now :)..

Upvotes: 1

Views: 4904

Answers (2)

netcoder
netcoder

Reputation: 67695

If you want to modify the query string, it's easier to simply modify the GET variables and rebuild the query string:

$params = $_GET;
$params['layout'] = 'new_layout';

Then:

<a href="index.php?<?php echo http_build_query($params); ?>">...</a>

Although you could also do:

<a href="index.php?<?php echo preg_replace('/(^|&)layout=[^&]*/', '\\1layout=new_layout', $_SERVER['QUERY_STRING']; ?>">...</a>

Upvotes: 6

mjec
mjec

Reputation: 1817

Think about directly parsing the $_GET paramaters to build your url.

I think what you want to do is have the link going to index.php with all the same parameters as you have at the moment, but changing layout to grid. I'd suggest you do something like this:

<?php
// make a copy of the $_GET array with all the parameters from the query string
$params = $_GET;
// set layout=grid regardless of whether layout was set before or its value
$params['layout'] = 'grid';
// generate a query string to append to your urls.
// Note that &amp; is used as the arg separator; this is necessary for XHTML and advised for HTML
$queryString = http_build_query($params, '', '&amp;');
?>

href="index.php?<?php echo $queryString; ?>">

This is much easier than trying to edit and fix the $_SERVER['QUERY_STRING'] yourself.

Upvotes: 0

Related Questions