Replacing Querystring Values in URLs

By Nick Little on August 6, 2008 at 6:30 am in General, Technical

There are many times in a programmer’s career when regular expressions are extremely useful. Sadly, many programmers do not know regular expressions well enough to use them when the situation requires it. This post shows how easy it is to replace the contents of querystring variables in a URL using regular expressions.

function replaceQueryString($url, $key, $value = NULL)
{
  $url = ereg_replace('[\?&]'.$key.'=[^&#]*(#?)', '\\1', ereg_replace('([\?&])'.$key.'=[^&#]*&', '\\1', $url));

  if ($value === NULL)
    return $url;
  else if (($pound = strpos($url, '#')) === false)
    return $url.(strpos($url, '?') === false ? '?' : '&').$key.'='.urlencode($value);
  else
    return substr($url, 0, $pound).(($question = strpos($url, '?')) === false || $question > $pound ? '?' : '&').$key.'='.urlencode($value).substr($url, $pound);
}

The first line of the function uses regular expressions to remove the existing query string value from the url. Next, the correct point of entry is found for the new value to be inserted. Finally, the new value is inserted into the url. All that in under ten lines of code.