Created
November 30, 2019 10:53
-
-
Save pasmat/8867d381c4bb3193477e35756c80764f 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 doing dynamic redirects based on current url.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
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