Skip to content

Instantly share code, notes, and snippets.

@flayder
Created September 21, 2020 13:58
Show Gist options
  • Save flayder/b7bb30360e2d60e78cd6cbfa2c57a83f to your computer and use it in GitHub Desktop.
Save flayder/b7bb30360e2d60e78cd6cbfa2c57a83f to your computer and use it in GitHub Desktop.
function replace_query_parameter($name, $arr_replace, $delete = []) {
$url = $_SERVER["REQUEST_URI"];
$regExp = "/{$name}\=[a-z0-9\[\]\%]*/i";
if( count($delete) > 0 ) {
foreach ($delete as $del) {
$url = preg_replace("/{$del}\=[a-z0-9\[\]\%]*/i", "", $url);
}
}
$urlstring = implode('&', array_map(
function ($v, $k) { return sprintf("%s=%s", $k, $v); },
$arr_replace,
array_keys($arr_replace)
));
if( preg_match($regExp, $url) ) {
$url = preg_replace($regExp, $urlstring."&", $url);
} else {
if(strpos($url, "?") !== false)
$url .= "&" . $urlstring;
else
$url .= "?" . $urlstring;
}
$url = preg_replace("/&{2,}/", "&", $url);
if(substr($url, -1) == "&") {
$url = substr($url, 0, -1);
}
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment