Search code examples
phpparse-url

php parse_url reverse -- parsed url


Is there a way to reverse the url from a parsed url?

$url = 'http://www.domain.com/dir/index.php?query=blabla#more_bla';
$parse = parse_url($url);
print_r($parse);
/*
array(
 'scheme'=>'http://',
 etc....
)
*/
$revere = reverse_url($parse); // probably does not exist but u get the point

echo $reverse;
//outputs:// "http://www.domain.com/dir/index.php?query=blabla#more_bla"

Or if there is a way validate a url that is missing part of its recommended urls e.g

www.mydomain.com

mydomain.com

should all return http://www.mydomain.com or with correct sub domain


Solution

  • You should be able to do

    http_build_url($parse)
    

    NOTE: http_build_url is only available by installing pecl_http.

    According to the docs it's designed specifically to handle the output from parse_url. Both functions handle anchors, query params, etc so there are no "other properties not mentioned on the $url".

    To add http:// when it's missing, use a basic check before parsing it:

    if (strpos($url, "http://") != 0)
        $url = "http://$url";