Hello.
I'm developing a site which has links for switching languages. The links reload the current page with ?land=fr or ?lang=en. These are stored in a session variable so that the query doesn't get appended every time.
This worked fine until I started adding pages with other HTTP queries. I was confronted with the problem of adding a parameter with a value to a URL which already has one or more ( with ? and & ). I wrote a function to solve this, and decided to make it more flexible so as to handle any query, not just the ?lang= one. The function expects
addQuery('lang','en')
It works but it seems so convoluted that I feel like I'm trying to reinvent the wheel:
function addQuery($param,$val) {
$uri = $_SERVER['REQUEST_URI'];
$query = $param."=".$val;
$prefix = (strpos($uri,"?")) ? "&" : "?";
$link = (strpos($uri,$param)) ? eregi_replace($param."=".$_GET[$param],$query,$uri) : $uri.$prefix.$query;
echo "<a href=\"$link\"></a>";
}
I don't have a lot of experience in PHP and I was wondering how other people were dealing with this problem. Is there a function which does this exact same thing?
Thanks.