我一直在努力寻找一个有效的url解析器,php自己不包含子域名或扩展名。在php.net上,许多用户做出了贡献并做到了这一点:
function parseUrl($url) {
$r = "^(?:(?P<scheme>\w+)://)?";
$r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
$r .= "(?P<host>(?:(?P<subdomain>[-\w\.]+)\.)?" . "(?P<domain>[-\w]+\.(?P<extension>\w+)))";
$r .= "(?::(?P<port>\d+))?";
$r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
$r .= "(?:\?(?P<arg>[\w=&]+))?";
$r .= "(?:#(?P<anchor>\w+))?";
$r = "!$r!"; // Delimiters
preg_match ( $r, $url, $out );
return $out;
}
不幸的是它在带有' - '的路径上失败了,我不能在我的生活中锻炼如何修改它以接受路径名中的' - '。
由于
答案 0 :(得分:1)
使用现有的parse_url函数然后从“主机”索引解析子域要容易得多。
示例:
$url = 'http://username:password@subdomain.hostname.tld/path?arg=value#anchor';
$urlInfo = parse_url($url);
$host = $urlInfo['host'];
$subdomain = substr($host, 0, strpos($host, '.'));
$tld = substr($host, strrpos($host, '.') + 1);
答案 1 :(得分:1)
试试这个......
function parseUrl($url) {
$r = "^(?:(?P<scheme>\w+)://)?";
$r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
$r .= "(?P<host>(?:(?P<subdomain>[-\w\.]+)\.)?" . "(?P<domain>[-\w]+\.(?P<extension>\w+)))";
$r .= "(?::(?P<port>\d+))?";
$r .= "(?P<path>[\w/-]*/(?P<file>[\w-]+(?:\.\w+)?)?)?";
$r .= "(?:\?(?P<arg>[\w=&]+))?";
$r .= "(?:#(?P<anchor>\w+))?";
$r = "!$r!";
preg_match ( $r, $url, $out );
return $out;
}
我在路径和文件中添加了破折号