Created
September 16, 2020 10:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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