function sgp($url,$varname,$value){
if(is_array($varname)){
foreach($varname as $i=>$n){
$v=(is_array($value))?(isset($value[$i])?$value[$i]:NULL):$value;
$url=sgp($url,$n,$v);
}
return $url;
}
preg_match('/^([^?]+)(\?.*?)?(#.*)?$/',$url,$matches);
$gp=(isset($matches[2]))?$matches[2]:'';
if(!$gp)return $url;
$pattern="/([?&])$varname=.*?(?=&|#|\z)/";
if(preg_match($pattern,$gp)){
$substitution=($value!=='')?"\${1}$varname=".preg_quote($value):'';
$newgp=preg_replace($pattern,$substitution,$gp);
$newgp=preg_replace('/^&/','?',$newgp);
}
else{
$s=($gp)?'&':'?';
$newgp=$gp.$s.$varname.'='.$value;
}
$anchor=(isset($matches[3]))?$matches[3]:'';
$newurl=$matches[1].$newgp.$anchor;
$newurl=rtrim($newurl,'&');
$newurl=str_replace('&&','&',$newurl);
$newurl=str_replace('?&','?',$newurl);
return $newurl;
}
Использование:
Замена 1 параметра
<a href="<?=sgp($url,'key',$value)?>">test</a>
Удаление 1 параметра
<a href="<?=sgp($url,'key','')?>">test</a>
Замена более 1 параметра
<a href="<?=sgp($url,array('key1','key2'),array($value1,$value2))?>">test</a>
Удаление более 1 параметра
<a href="<?=sgp($url,array('key1','key2'),NULL)?>">test</a>
http://webew.ru/articles/743.webew
http://webew.ru/articles/5510.webew