Skip to content

Instantly share code, notes, and snippets.

@pasmat
Created November 30, 2019 10:54
Show Gist options
  • Save pasmat/b34edd3a498ac95f58119bcc6399c1b5 to your computer and use it in GitHub Desktop.
Save pasmat/b34edd3a498ac95f58119bcc6399c1b5 to your computer and use it in GitHub Desktop.
An function to modify parameters within url, either to change them or replace them. Useful when updating url based on changes on page dynamically without a reload.
static function changeParameters($url, $parameters)
{
$urlParts = parse_url($url);
$url = "";
if (isset($urlParts['scheme'])) {
$url .= $urlParts['scheme'] . "://";
}
if (isset($urlParts['host'])) {
$url .= $urlParts['host'];
}
if (isset($urlParts['path'])) {
$url .= $urlParts['path'];
}
$query = isset($urlParts['query']) ? $urlParts['query'] : "";
$urlParameters = explode("&", $query);
$urlParameterValuesByKey = new stdClass();
foreach ($urlParameters as $urlParameter) {
$equalsIndex = strrpos($urlParameter, "=");
if ($equalsIndex) {
$urlParameterValuesByKey->{substr($urlParameter, 0, $equalsIndex)} = substr($urlParameter, $equalsIndex + 1);
} else {
$urlParameterValuesByKey->{$urlParameter} = null;
}
}
foreach ($parameters as $key => $value) {
if(!is_string($value)) {
unset($urlParameterValuesByKey->{$key});
} else {
$urlParameterValuesByKey->{$key} = $value;
}
}
$query = "";
foreach ($urlParameterValuesByKey as $key => $value) {
if (strlen($query) === 0) {
$query .= "?";
}
if (strlen($query) > 1) {
$query .= "&";
}
if (is_string($value)) {
$query .= $key . "=" . $value;
} else {
$query .= $key;
}
}
$url .= $query;
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment