Reverse parse_url() PHP Function

This function does the opposite process of the parse_url() function in PHP. It converts the full array of components back into a URL string.

/**
 * Generate URL from its components.
 *
 * This is essentially the opposite of built-in php function, parse_url().
 *
 * @param array $parsedUrl
 *   The parts of the parse_url array.
 *
 * @return string
 *   The reconstructed URL.
 */
function rebuild_url(array $parsedUrl): string {
  $parts = [
    'credentials' => '',
    'port' => '',
  ];

  $parts['scheme'] = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] . '://' : '';
  $parts['host'] = $parsedUrl['host'] ?? '';

  if (isset($parsedUrl['port'])) {
    if (($parsedUrl['scheme'] === 'http' && $parsedUrl['port'] !== '80') || ($parsedUrl['scheme'] === 'https' && $parsedUrl['port'] !== '443')) {
      $parts['port'] = ':' . $parsedUrl['port'];
    }
  }

  $parts['username'] = $parsedUrl['username'] ?? '';
  $parts['password'] = $parsedUrl['password'] ?? '';
  if (!empty($parts['username']) && !empty($parts['password'])) {
    $parts['credentials'] = $parts['username'] . ':' . $parts['password'] . '@';
  }

  $parts['path'] = $parsedUrl['path'] ?? '';
  $parts['query'] = isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';
  $parts['fragment'] = isset($parsedUrl['fragment']) ? '#' . $parsedUrl['fragment'] : '';

  return $parts['scheme'] .
    $parts['credentials'] .
    $parts['host'] .
    $parts['port'] .
    $parts['path'] .
    $parts['query'] .
    $parts['fragment'];
}

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.