Connecting Tech Pros Worldwide Forums | Help | Site Map

How to replace an item in the url search string

laredotornado@zipmail.com
Guest
 
Posts: n/a
#1: Mar 3 '06
Hi, Using PHP 4, what is the most elegant way to replace a parameter
value in a url query string? I want to replace the "Order" parameter,
but it could occur anywhere in the query string.

myfile.php?Param1=Hi+there&Order=ColumnA&Param3=By e+Bye
myfile.php?Order=ColumnA
myfile.php?Param1=Anotehr+example&Order=ColumnA

after applying this function, I'd like the result of the above examples
to be

myfile.php?Param1=Hi+there&Order=ColumnB&Param3=By e+Bye
myfile.php?Order=ColumnB
myfile.php?Param1=Anotehr+example&Order=ColumnB

Thanks for your help, - Dave


samudas
Guest
 
Posts: n/a
#2: Mar 3 '06

re: How to replace an item in the url search string


This is really ugly and there's probably a better way. In php5 it would
be a piece of cake because you'd have the http_build_query function.
You might also try using a regex. I'm going to trust that you know how
to get the query string yourself.

<?php
$str = 'Param=Hi+there&Order=ColumnA&Param3=Bye+Bye';
parse_str($str, $ar);
if ($ar['Order']) {
$ar['Order'] = 'ColumnB';
}
$newstr = '';
foreach($ar as $key => $value) {
$newstr .= $key . '=' . urlencode($value) . '&';
}
print rtrim($newstr, '&');
?>

Richard Levasseur
Guest
 
Posts: n/a
#3: Mar 4 '06

re: How to replace an item in the url search string


PEAR has a small handy class that does this:

http://pear.php.net/package/Net_URL

Closed Thread