/**
* 解析 url 信息,支持中文,可完全替代parse_url 并且兼容原 parse_url
*
* - parse_url('https://wgx:dd@www.baidu.com:80/1?a=1')
* - parse_url('https://www.baidu.com/search#print')
* - parse_url('file:///xxx/xxx/xxx')
* - parse_url('ftp://www.baidu.com')
* - parse_url('?a=1')
* - parse_url('www.baidu.com/aa/1')
* @author Renew
*/
function parse_url($uri, $component = -1){
preg_match('/^(?:([A-Za-z-\x{4e00}-\x{9fa5}+&@#]+):)?(\/{0,3})?(?:(\w+:\w+)@)?([0-9.\-A-Za-z-\x{4e00}-\x{9fa5}]+)?(?::(\d+))?(?:(\/[^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/ui', $uri, $data);
$scheme = isset($data[1]) ? $data[1] : null;
$up = explode(':', isset($data[3]) ? $data[3] : null);
$host = isset($data[4]) ? $data[4] : null;
$port = isset($data[5]) ? $data[5] : null;
$path = isset($data[6]) ? $data[6] : null;
if ($path && substr($path, 0, 1) != '/') $path = '/' . $path;
$query = isset($data[7]) ? $data[7] : null;
$fragment = isset($data[8]) ? $data[8] : null;
if ($scheme === 'file') {
$path = "/{$host}{$path}";
$host = null;
}
$user = (!empty($up) && isset($up[0])) ? $up[0] : null;
$pass = (!empty($up) && isset($up[1])) ? $up[1] : null;
$intComponent = is_numeric($component) ? (int)$component : -1;
switch ($intComponent) {
case PHP_URL_SCHEME:
return $scheme;
case PHP_URL_HOST:
return $host;
case PHP_URL_PORT:
return $port;
case PHP_URL_USER:
return $user;
case PHP_URL_PASS:
return $pass;
case PHP_URL_PATH:
return $path;
case PHP_URL_QUERY:
return $query;
case PHP_URL_FRAGMENT:
return $fragment;
default:
$result = [];
if ($scheme != null) $result['scheme'] = $scheme;
if ($host != null) $result['host'] = $host;
if ($port != null) $result['port'] = (int)$port;
if ($user != null) $result['user'] = $user;
if ($pass != null) $result['pass'] = $pass;
if ($path != null) $result['path'] = $path;
if ($query != null) $result['query'] = $query;
if ($fragment != null) $result['fragment'] = $fragment;
if ($component && is_string($component)) {
return isset($result[$component]) ? $result[$component] : null;
}
return $result;
}
}
网友评论