user1906005
user1906005

Reputation: 85

remove one querty string from REQUEST_URI (PHP)

I'm having an issue removing a particular query string from a url. I want to keep the rest of the queries but simply dump the last one. The problem is the query string could have a different value each time, so I dont know how to do this.

For example my site url might be:

http://sitename.com/index.php?Cat=Bus&Origin=UK

What I want to do, is keep Cat=Bus and remove Origin=UK

So if I try to change the origin to Germany I write:

echo '<a href="'.$_SERVER['REQUEST_URI'].'&Origin=Germany">Germany</a>';

So it takes the page it is on:

http://sitename.com/index.php?Cat=Bus&Origin=UK

Using Request_URI. I want to then strip it of &Origin=* Then once thats done pass it into a string and add whatever the new origin is on the end.

I figure:

$theURI = $_SERVER['REQUEST_URI'];

But I have no idea how to go from start to finish.

$amended = $theURI - '&Origin=*'

and then end up with

echo '<a href="'.$amended.'&Origin=Germany">Germany</a>';

I just don't know how to express that $amended function in PHP.

Could somebody help? This is being used for sorting between countries

Upvotes: 0

Views: 2265

Answers (2)

Teodor Blazhev
Teodor Blazhev

Reputation: 56

If you know the exact variables and they are not that many, you can do with Dale's comment:

echo '<a href="/index.php?Cat=' . $_GET['Cat'] . '&Origin=Germany">Germany</a>';

If not you could use str_replace:

$url = $_SERVER['REQUEST_URI'];
$url = str_replace("origin=" . $_GET["origin"], "", $url);
$url = preg_replace("#&+#", "&", $url);
... 
echo "<a href='" . $url . "&origin=Germany"'>Germany</a>";

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22395

Depending on how you're getting the origin (static url vs dynamic url), it's a simple manipulation of the $_GET superglobal.

$url = $_SERVER['REQUEST_URI']; //edit: I usually use $_SERVER['PHP_SELF'], so try this if REQUEST_URI fails
$get_param = $value; //$value can be germany, england, poland, etc etc
$url .= "&Origin=".$get_param;
echo "<a href='".$url."'>$get_param</a>";

I hope this helps

Upvotes: 1

Related Questions