Skip to content

Instantly share code, notes, and snippets.

@lutzissler
Created September 16, 2020 10:30
Show Gist options
  • Save lutzissler/d7e66948c276a057363d8db8050f0f5d to your computer and use it in GitHub Desktop.
Save lutzissler/d7e66948c276a057363d8db8050f0f5d to your computer and use it in GitHub Desktop.
Encode a URL (or just a path) with `rawurlencode()` to make it pass the W3C validator in HTML source and, of course, be a valid URL.
function encode_url($url) {
$parsed_url = parse_url($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" . implode('/', array_map('rawurlencode', explode('/', $path))) . "$query$fragment";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment