Version: 1.0

Type: Function

Category: HTTP

License: GNU General Public License

Description: A function to add or replace the value of a particular query parameter. It assumes typical &-separated parameters. -- Parameters -- $query The query string, still url-encoded. $param The query parameter to change the value of. Not url-encoded. $value The new value for the parameter. Not url-encoded. Returns the new query string, with parameter names and values url-encoded.



/**
 * Add or replace the value of a particular query parameter.
 * Assumes typical &-separated parameters. Case-sensitive.
 *
 * $query   The query string, still url-encoded.
 * $param   The query parameter to change the value of. Not url-encoded.
 * $value   The new value for the parameter. Not url-encoded.
 * Returns the new query string, with parameter names and values url-encoded.
 */
function ReplaceQueryValue ($query, $param, $value)
{
    // Prepend & so all parameters are delimited by &...=
    if (!empty($query)) $query = '&' . $query;
    $param = '&' . urlencode($param) . '=';
    $value = urlencode($value);

    // Find occurance of parameter
    $index = strpos ($query, $param);
    if ($index === false)
    {
        // Not present. Append param/value.
        $query .= $param . $value;
    }
    else
    {
        // Delimit & replace value part.
        $valstart = $index + strlen ($param);
        $valend = strpos ($query, '&', $valstart);
        if ($valend === false)  $valend = strlen ($query);
        $query = substr_replace ($query, $value, $valstart,
                                 $valend - $valstart);
    }
    return substr ($query, 1);
}