Convert a parsed URL back to a string.

<p>Basically the opposite of parse_url. Specify a set of components
and this function turns it back into a string again.</p>

@see parse_url()
@param array $parsed_url
@return string
172874
public static function parsedURLToString($parsed_url) {

		$components = [];

		if(!empty($parsed_url['scheme'])){

			$components['scheme'] = $parsed_url['scheme'] . '://';
		}

		$components['user'] = '';
		$components['pass'] = '';

		if(!empty($parsed_url['user'])){

			$components['user'] = $parsed_url['user'];
		}

		if(!empty($parsed_url['pass'])){

			$components['pass'] = ':' . $parsed_url['pass'];
		}

		if($components['user'] || $components['pass']){

			$components['pass'] = $components['pass'] . '@';
		}

		if(!empty($parsed_url['host'])){

			$components['host'] = $parsed_url['host'];
		}

		if(!empty($parsed_url['port'])){

			$components['port'] = ':' . $parsed_url['port'];
		}

		if(!empty($parsed_url['path'])){

			$components['path'] = $parsed_url['path'];
		}

		if(!empty($parsed_url['query'])){

			$components['query'] = '?' . $parsed_url['query'];
		}

		if(!empty($parsed_url['fragment'])){

			$components['fragment'] = '#' . $parsed_url['fragment'];
		}

		return implode('', $components);
	}
750291
protected function buildUrl(array $parsedUrl)
    {
        if (true === isset($parsedUrl['scheme'])) {
            $scheme = $parsedUrl['scheme'].'://';
        } else {
            $scheme = '';
        }

        if (true === isset($parsedUrl['host'])) {
            $host = $parsedUrl['host'];
        } else {
            $host = '';
        }

        if (true === isset($parsedUrl['port'])) {
            $port = ':'.$parsedUrl['port'];
        } else {
            $port = '';
        }

        if (true === isset($parsedUrl['user'])) {
            $user = (string) $parsedUrl['user'];
        } else {
            $user = '';
        }

        if (true === isset($parsedUrl['pass'])) {
            $pass = ':'.$parsedUrl['pass'];
        } else {
            $pass = '';
        }

        if (false === empty($user) || false === empty($pass)) {
            $host = '@'.$host;
        }

        if (true === isset($parsedUrl['path'])) {
            $path = (string) $parsedUrl['path'];
        } else {
            $path = '';
        }

        if (true === isset($parsedUrl['query'])) {
            $query = '?'.$parsedUrl['query'];
        } else {
            $query = '';
        }

        if (true === isset($parsedUrl['fragment'])) {
            $fragment = '#'.$parsedUrl['fragment'];
        } else {
            $fragment = '';
        }

        return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;

    }
151701
public static function parse($url)
    {
        $scheme = substr($url, 0, strpos($url, ':'));
        if (strpos($scheme, '+')) {
            $scheme = substr($scheme, 0, strpos($scheme, '+'));
        }

        if (!$scheme) {
            throw new \Exception(sprintf('The url \'%s\' could not be parsed', $url));
        }

        if (isset(static::$schemeMap[$scheme])) {
            $className = static::$schemeMap[$scheme];
        } else {
            $className  = static::currentNamespace() . '\\' . ucfirst($scheme) . 'Dsn';
            if (!class_exists($className)) {
                $className  = static::currentClass();
            }
        }
        return new $className($url);
    }
583012
public static function parse_url_brackets(&$url)
    {
        // #1487672: special handling of square brackets,
        // URL regexp allows [] characters in URL, for example:
        // "http://example.com/?a[b]=c". However we need to handle
        // properly situation when a bracket is placed at the end
        // of the link e.g. "[http://example.com]"
        // Yes, this is not perfect handles correctly only paired characters
        // but it should work for common cases

        if (preg_match('/(\\[|\\])/', $url)) {
            $in = false;
            for ($i=0, $len=strlen($url); $i<$len; $i++) {
                if ($url[$i] == '[') {
                    if ($in)
                        break;
                    $in = true;
                }
                else if ($url[$i] == ']') {
                    if (!$in)
                        break;
                    $in = false;
                }
            }

            if ($i < $len) {
                $suffix = substr($url, $i);
                $url    = substr($url, 0, $i);
            }
        }

        // Do the same for parentheses
        if (preg_match('/(\\(|\\))/', $url)) {
            $in = false;
            for ($i=0, $len=strlen($url); $i<$len; $i++) {
                if ($url[$i] == '(') {
                    if ($in)
                        break;
                    $in = true;
                }
                else if ($url[$i] == ')') {
                    if (!$in)
                        break;
                    $in = false;
                }
            }

            if ($i < $len) {
                $suffix = substr($url, $i);
                $url    = substr($url, 0, $i);
            }
        }

        return $suffix;
    }
537300
public static function preprocess($url_parsed) {
        if (($url_parsed['host'] === 'youtu.be')
            && preg_match('/^\/([a-zA-Z0-9\-_]+?)$/', $url_parsed['path'], $matches)
        ) {
            $params = self::parseParams($url_parsed);
            $params['vid'] = $matches[1];
            return array(
                'path_type' => 'video',
                'params' => &$params,
            );
        } elseif (preg_match('/^\/watch$/', $url_parsed['path'])) {
            $params = self::parseParams($url_parsed);
            if ($params == FALSE) return FALSE;
            if (!isset($params['vid']) || ($params['vid'] == FALSE)) return FALSE;
            return array(
                'path_type' => 'video',
                'params' => &$params,
            );
        } elseif (preg_match('/^\/v\/([a-zA-Z0-9\-_]+?)(&.+?|)(|\/)$/', $url_parsed['path'], $matches)) {
            $params = self::parseParams($url_parsed);
            $params['vid'] = $matches[1];
            if (!empty($matches[2])) {
                parse_str($matches[2], $embed_query);
                $params += $embed_query;
            }
            if (!isset($params['vid']) || ($params['vid'] == FALSE)) return FALSE;
            return array(
                'path_type' => 'video',
                'params' => &$params,
            );
        } elseif ((preg_match('/^\/view_play_list$/', $url_parsed['path'])) ||
            (preg_match('/^\/playlist$/', $url_parsed['path']))) {
            parse_str($url_parsed["query"], $query);
            $location = preg_replace('/([a-z]+?)\.youtube\.com/', '$1', strtolower($url_parsed["host"]));
            return array(
                'path' => $url_parsed['path'],
                'path_type' => 'playlist',
                'query' => &$query,
                'location' => $location,
            );
        }
        return FALSE;
    }
206613
public static function normalize(string $url, array $parameters = []):string
    {
        $normalizedUrl = $url;
        if (!empty($parameters)) {
            $normalizedUrl .= (false !== strpos($url, '?') ? '&' : '?') . http_build_query($parameters, '', '&');
        }
        return $normalizedUrl;
    }
487852
public static function parse_url($url, int $component = -1) {
		ref\cast::string($url, true);
		ref\mb::trim($url);

		// Before we start, let's fix scheme-agnostic URLs.
		$url = \preg_replace('/^:?\/\//', 'https://', $url);

		// If an IPv6 address is passed on its own, we
		// need to shove it in brackets.
		if (\filter_var($url, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
			$url = "[$url]";
		}

		// The trick is to urlencode (most) parts before passing
		// them to the real parse_url().
		$encoded = \preg_replace_callback(
			'%([a-zA-Z][a-zA-Z0-9+\-.]*)?(:?//)?([^:/@?&=#\[\]]+)%usD',
			function ($matches) {
				$matches[3] = \urldecode($matches[3]);
				return $matches[1] . $matches[2] . $matches[3];
			},
			$url
		);

		// Before getting the real answer, make sure
		// there is a scheme, otherwise PHP will assume
		// all there is is a path, which is stupid.
		if (\PHP_URL_SCHEME !== $component) {
			$test = \parse_url($encoded, \PHP_URL_SCHEME);
			if (! $test) {
				$encoded = "blobfolio://$encoded";
			}
		}

		$parts = \parse_url($encoded, $component);

		// And now decode what we've been giving. Let's
		// also take a moment to translate Unicode hosts
		// to ASCII.
		if (\is_string($parts) && \PHP_URL_SCHEME !== $component) {
			$parts = \str_replace(' ', '+', \urldecode($parts));

			if (\PHP_URL_HOST === $component) {
				// Fix Unicode.
				if (\function_exists('idn_to_ascii')) {
					$parts = \explode('.', $parts);
					ref\file::idn_to_ascii($parts);
					$parts = \implode('.', $parts);
				}

				// Lowercase it.
				ref\mb::strtolower($parts, false);

				// Get rid of trailing periods.
				$parts = \ltrim($parts, '.');
				$parts = \rtrim($parts, '.');

				// Standardize IPv6 formatting.
				if (0 === \strpos($parts, '[')) {
					$parts = \str_replace(array('[', ']'), '', $parts);
					ref\sanitize::ip($parts, true);
					$parts = "[{$parts}]";
				}
			}
		}
		elseif (\is_array($parts)) {
			foreach ($parts as $k=>$v) {
				if (! \is_string($v)) {
					continue;
				}

				if ('scheme' !== $k) {
					$parts[$k] = \str_replace(' ', '+', \urldecode($v));
				}
				// Remove our pretend scheme.
				elseif ('blobfolio' === $v) {
					unset($parts[$k]);
					continue;
				}

				if ('host' === $k) {
					// Fix Unicode.
					if (\function_exists('idn_to_ascii')) {
						$parts[$k] = \explode('.', $parts[$k]);
						ref\file::idn_to_ascii($parts[$k]);
						$parts[$k] = \implode('.', $parts[$k]);
					}

					// Lowercase it.
					ref\mb::strtolower($parts[$k], false);

					// Get rid of trailing periods.
					$parts[$k] = \ltrim($parts[$k], '.');
					$parts[$k] = \rtrim($parts[$k], '.');

					// Standardize IPv6 formatting.
					if (0 === \strpos($parts[$k], '[')) {
						$parts[$k] = \str_replace(array('[', ']'), '', $parts[$k]);
						ref\sanitize::ip($parts[$k], true);
						$parts[$k] = "[{$parts[$k]}]";
					}
				}
			}
		}

		return $parts;
	}
754696
public static function parseUrl($url)
    {
        if (!\is_string($url)) {
            throw new \InvalidArgumentException('URL must be a string');
        }

        $encodedUrl = preg_replace_callback(
            '%[^:/@?&=#]+%u',
            function ($matches) { return rawurlencode($matches[0]); },
            $url
        );

        $parts = \is_string($encodedUrl) ? parse_url($encodedUrl) : false;
        if ($parts === false) {
            throw new \InvalidArgumentException("Malformed URL: {$url}");
        }

        return $parts;
    }
605232
public static function fromUrl($url)
    {
        $elements = parse_url($url);
        $elements['pathinfo'] = isset($elements['path']) ? $elements['path'] : '';

        if (isset($elements['query'])) {
            parse_str($elements['query'], $queryParams);
            $elements['queryParams'] = $queryParams;
        }

        // Remove unwanted keys returned by parse_url() so that we don't have them as properties.
        unset($elements['path'], $elements['query'], $elements['user'], $elements['pass'], $elements['fragment']);

        return new static($elements);
    }
657379
protected function parseUrlParams($url_params)
    {
        if ($url_params != '#' && (is_array($url_params) || (strpos($url_params, 'http') !== 0 && strpos($url_params, '/') !== 0))) {
            if (!is_array($url_params))
                $url_params = array($url_params);
            $url_to = Rails::application()->router()->urlFor($url_params, true);
        } else {
            $url_to = $url_params;
        }
        return $url_to;
    }
732961
public static function urlEncode ($parms) {
    $payload = array();

    foreach ($parms as $key => $value) {
      if (is_array($value)) {
        foreach ($value as $item) {
          $payload[] = urlencode($key) . '=' . urlencode($item);
        }
      } else {
        $payload[] = urlencode($key) . '=' . urlencode($value);
      }
    }

    return implode('&', $payload);
  }
1317925
static function parse(string $url, ?int $preferredFormat = self::ABSOLUTE)
    {
        $components = parse_url($url);

        if ($components === false) {
            throw new InvalidUrlException(sprintf('The given URL "%s" is invalid', $url));
        }

        $query = [];

        if (isset($components['query'])) {
            parse_str($components['query'], $query);
        }

        return new static(
            $components['scheme'] ?? null,
            $components['host'] ?? null,
            $components['port'] ?? null,
            $components['path'] ?? '',
            $query,
            $components['fragment'] ?? null,
            $preferredFormat
        );
    }
152781
private static function checkParsedUrl(array $parsed)
    {
        $scheme   =& $parsed['scheme'];
        $user     =& $parsed['user'];
        $pass     =& $parsed['pass'];
        $host     =& $parsed['host'];
        $port     =& $parsed['port'];
        $path     =& $parsed['path'];
        $path     = '/'.ltrim($path, '/'); // If / is missing for path.
        $query    =& $parsed['query'];
        $fragment =& $parsed['fragment'];

        return compact(
            'scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment'
        );
    }
461096
protected function parseUrl($url)
    {
        if (strpos($url, '//') === 0) {
            $url = "http:$url";
        }

        $this->info = parse_url($url);

        if (isset($this->info['query'])) {
            parse_str($this->info['query'], $this->info['query']);

            array_walk_recursive($this->info['query'], function (&$value) {
                $value = urldecode($value);
            });
        }

        if (isset($this->info['path'])) {
            $this->setPath($this->info['path']);
        }
    }
873548
public function parseURL($url)
	{
		try {
			$u = parse_url($url);
			if(isset($u["query"]))
	        	$this->parseQueryString($u["query"]);
	        if(isset($u["fragment"]))
	        	$this->parseQueryString($u["fragment"]);
	    } catch (Exception $e) {
	    } 
	}
404138
public static function unparse($parsed)
    {
        if (empty($parsed)) return '';

        $parsed = self::checkParsedUrl($parsed);

        $url  = self::getUrl($parsed);
        $url .= self::getQuery($parsed);
        $url .= self::getFragment($parsed);

        return $url;
    }
280451
public function urlWithQuerystring(string $url, string $allowedParameters = null) : string
    {
        if (!$allowedParameters) {
            return $url;
        }

        $allowedParameters = str_start($allowedParameters, '/');
        $allowedParameters = str_finish($allowedParameters, '/');

        $currentQuery = collect(request()->query())->filter(function ($value, $parameter) use ($allowedParameters) {
            return preg_match($allowedParameters, sprintf('%s=%s', $parameter, $value));
        });

        if (!$newQuery = http_build_query($currentQuery->all())) {
            return $url;
        };

        return sprintf('%s?%s', $url, $newQuery);
    }