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
These are the two functions I use for decomposing and rebuilding URLs:
function http_parse_query($query) { $parameters = array(); $queryParts = explode('&', $query); foreach ($queryParts as $queryPart) { $keyValue = explode('=', $queryPart, 2); $parameters[$keyValue[0]] = $keyValue[1]; } return $parameters; } function build_url(array $parts) { return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') . ((isset($parts['user']) || isset($parts['host'])) ? '//' : '') . (isset($parts['user']) ? "{$parts['user']}" : '') . (isset($parts['pass']) ? ":{$parts['pass']}" : '') . (isset($parts['user']) ? '@' : '') . (isset($parts['host']) ? "{$parts['host']}" : '') . (isset($parts['port']) ? ":{$parts['port']}" : '') . (isset($parts['path']) ? "{$parts['path']}" : '') . (isset($parts['query']) ? "?{$parts['query']}" : '') . (isset($parts['fragment']) ? "#{$parts['fragment']}" : ''); } // Example $parts = parse_url($url); if (isset($parts['query'])) { $parameters = http_parse_query($parts['query']); foreach ($parameters as $key => $value) { $parameters[$key] = $value; // do stuff with $value } $parts['query'] = http_build_query($parameters); } $url = build_url($parts);
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With