另一个实现:
function build_url(array $elements) {
$e = $elements;
return
(isset($e['host']) ? (
(isset($e['scheme']) ? "$e[scheme]://" : '//') .
(isset($e['user']) ? $e['user'] . (isset($e['pass']) ? ":$e[pass]" : '') . '@' : '') .
$e['host'] .
(isset($e['port']) ? ":$e[port]" : '')
) : '') .
(isset($e['path']) ? $e['path'] : '/') .
(isset($e['query']) ? '?' . (is_array($e['query']) ? http_build_query($e['query'], '', '&') : $e['query']) : '') .
(isset($e['fragment']) ? "#$e[fragment]" : '')
;
}
结果应该是:
{
"host": "example.com"
}
/* //example.com/ */
{
"scheme": "https",
"host": "example.com"
}
/* https://example.com/ */
{
"scheme": "http",
"host": "example.com",
"port": 8080,
"path": "/x/y/z"
}
/* http://example.com:8080/x/y/z */
{
"scheme": "http",
"host": "example.com",
"port": 8080,
"user": "anonymous",
"query": "a=b&c=d",
"fragment": "xyz"
}
/* http://anonymous@example.com:8080/?a=b&c=d#xyz */
{
"scheme": "http",
"host": "example.com",
"user": "root",
"pass": "stupid",
"path": "/x/y/z",
"query": {
"a": "b",
"c": "d"
}
}
/* http://root:stupid@example.com/x/y/z?a=b&c=d */
{
"path": "/x/y/z",
"query": "a=b&c=d"
}
/* /x/y/z?a=b&c=d */