Created
October 6, 2023 17:20
-
-
Save matheusb-comp/1d607c854b7ef83776d7570d0ad45148 to your computer and use it in GitHub Desktop.
Parse and rebuild an URL adding new QueryString values
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 | |
function mergeUrlQuery(string $url, array $queryData = []): string | |
{ | |
$parts = parse_url($url); | |
if (empty($parts['host'])) throw new \InvalidArgumentException('url'); | |
$originalQuery = []; | |
if (!empty($parts['query'])) { | |
foreach (explode('&', $parts['query']) as $i => $el) { | |
list($k, $v) = explode('=', $el); | |
$key = $k ? rawurldecode($k) : $i; | |
$originalQuery[$key] = rawurldecode($v); | |
} | |
} | |
$query = array_merge($originalQuery, $queryData); | |
$url = ($parts['scheme'] ?? 'https') . '://'; | |
if (!empty($parts['user'])) $url .= $parts['user']; | |
if (!empty($parts['pass'])) $url .= ':' . $parts['pass']; | |
if (!empty($parts['user']) || !empty($parts['pass'])) $url .= '@'; | |
$url .= $parts['host']; | |
if (!empty($parts['port'])) $url .= ':' . $parts['port']; | |
if (!empty($parts['path'])) $url .= $parts['path']; | |
$url .= '?' . http_build_query($query, '', null, PHP_QUERY_RFC3986); | |
if (!empty($parts['fragment'])) $url .= '#' . $parts['fragment']; | |
return $url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment