Return to Snippet

Revision: 37899
at December 19, 2010 21:00 by mikael12


Initial Code
function modify_url($mod){
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    if (!$_SERVER['QUERY_STRING']) {$queryStart = "?";} else {$queryStart = "&";}
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= $queryStart.$key.'='.$value;
        }
    }
    return $url;
}

Initial URL
http://www.phpsnippets.info/easily-modify-url-parameters

Initial Description
Current URL http://www.example.com/page.php?p=5&show=list&style=2 and after 
$url = modify_url(array('p' => 4, 'show' => 'column')); 
URL will become http://www.example.com/page.php?p=4&show=column&style=2

Initial Title
Modify URL param

Initial Tags


Initial Language
PHP