Reputation: 15976
I want to add a query string to a URL, however, the URL format is unpredictable. The URL can be
http://example.com/page/
-> http://example.com/page/?myquery=string
http://example.com/page
-> http://example.com/page?myquery=string
http://example.com?p=page
-> http://example.com?p=page&myquery=string
These are the URLs I'm thinking of, but it's possible that there are other formats that I'm not aware of.
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Edit: I'm using Cbroe explanation and Passerby code. There is another function by Hamza but I guess it'd be better to use PHP functions and also have cleaner/shorter code.
Upvotes: 0
Views: 1727
Reputation: 14921
Some spaghetti Code:
echo addToUrl('http://example.com/page/','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page/wut/?aaa=2','myquery', 'string').'<br>';
echo addToUrl('http://example.com?p=page','myquery', 'string');
function addToUrl($url, $var, $val){
$array = parse_url($url);
if(isset($array['query'])){
parse_str($array['query'], $values);
}
$values[$var] = $val;
unset($array['query']);
$options = '';$c = count($values) - 1;
$i=0;
foreach($values as $k => $v){
if($i == $c){
$options .= $k.'='.$v;
}else{
$options .= $k.'='.$v.'&';
}
$i++;
}
$return = $array['scheme'].'://'.$array['host'].(isset($array['path']) ? $array['path']: '') . '?' . $options;
return $return;
}
Results:
http://example.com/page/?myquery=string
http://example.com/page?myquery=string
http://example.com/page/wut/?aaa=2&myquery=string
http://example.com?p=page&myquery=string
Upvotes: 1
Reputation: 10070
function addQuery($url,array $query)
{
$cache=parse_url($url,PHP_URL_QUERY);
if(empty($cache)) return $url."?".http_build_query($query);
else return $url."&".http_build_query($query);
}
// test
$test=array("http://example.com/page/","http://example.com/page","http://example.com/?p=page");
print_r(array_map(function($v){
return addQuery($v,array("myquery"=>"string"));
},$test));
Upvotes: 3
Reputation: 1268
You should try the http_build_query()
function, I think that's what you're looking for, and maybe a bit of parse_str()
, too.
Upvotes: 0
Reputation: 96326
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Depends on how failsafe – and thereby more complex – you want it to be.
The simplest way would be to look for whether there’s a ?
in the URL – if so, append &myquery=string
, else append ?myquery=string
. This should cover most cases of standards-compliant URLs just fine.
If you want it more complex, you could take the URL apart using parse_url
and then parse_str
, then add the key myquery
with value string
to the array the second function returns – and then put it all back together again, using http_build_query
for the new query string part.
Upvotes: 1