Arka Roy

Unparse a Parsed URL in PHP

PHP has a nice and very useful method parse_url to parse and split the url into applicable url components and return the list of component as associative array. But sometimes, you may need to reverse the process.

You may need to modify only the path or the query segment of a given url. The easy way to do this is to split the url into components, update the specific component you need and put the components back to form a complete url again.

The following method will put the components generated from parse_url back into a complete url.


function unparse_url($parsed_url)
    $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
    $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
    $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
    $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
    $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
    $pass     = ($user || $pass) ? "$pass@" : '';
    $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
    $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
    $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
    return "$scheme$user$pass$host$port$path$query$fragment";

I faced a situation where I needed this method to put back components into a complete url. If you want to know more about the parse_url method, check the documentation.

Other Articles

Custom Category Pagination in Jekyll

Jekyll is an awesome project. But how can we paginate only one type of post? Or what about custom permalink?

Validate IBAN in PHP

International Bank Account Number (IBAN) is an international standard for identifying account numbers. How can we make sure that an user enters a valid IBAN?