I’ve got a URL that I’m wanting to replace values if they’re there, but add if they’re not.
My URL would be for example: http://www.example.com/online/admin/users?p=Name&sort=user&dir=desc and I want to write a script that will write out the queries in the URL again if it exists already or add it if it doesn’t. I want to the write it to an “a” tag but with the different value I select for sort and dir
I found some code at a website called Add Querystring Variable
function add_querystring_var($url, $key, $value) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
if (strpos($url, '?') === false) {
return ($url . '?' . $key . '=' . $value);
} else {
return ($url . '&' . $key . '=' . $value);
}
}
My only problem is I’m not sure how to use it to do what I want.
This is the code I’ve got so far to go with it
add_querystring_var("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],"sort","lvl");
add_querystring_var("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],"dir","asc");
But I don’t know what to do from here as that isn’t writing anything out for me.
I know it will be simple but I’m new to this area of PHP. 😀
EDIT
Code so far
$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
function add_querystring_var($url, $key, $value) {
$urlarray = parse_url($url);
parse_str($urlarray['query'],$queryarray);
$queryarray[$key]=$value;
$queryarray = http_build_query($queryarray);
return http_build_url($url,array('query'=>$queryarray),HTTP_URL_JOIN_QUERY);
}
$url_id=add_querystring_var($url,"sort","lvl");
$url_id=add_querystring_var($url,"dir",$dir);
<?php echo '<a href="'.$url.'">New Anchor</a>'; ?>
But this returned blank. Any more ideas at all? Thanks for all the input so far guys.
I would recommend to use parse_url and parse_str
call like this
or for your specific case
Tested