Preg_match:在一个表达式中从 url 中获取最后两个域段
php.net 上有一个例子,如何分两步获取最后两个域段:
There is an example on php.net how to get last two domain segments in two steps:
<?php
//get host name from URL
preg_match("/^(http://)?([^/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}
";
/* Output is php.net */
?>
但是我怎样才能一步完成,只使用一个 preg_match 表达式?
But how can I do it in one step, using only one preg_match expression?
推荐答案
这段代码:
$domain = 'http://www.php.net/index.html';
$url = parse_url($domain);
$tokens = explode('.', $url['host']);
print_r($tokens);
会给你这个数据:
Array
(
[0] => www
[1] => php
[2] => net
)
我相信不需要正则表达式,因为很难用它们正确解析 URL.从生成的 $tokens 数组中,您可以轻松提取主机名的任何部分.
I believe there is no need for regexs as far as it's very hard to properly parse URL with them. From resulting $tokens array you can extract any part of host name easily.
更新:
print_r($url);
$url 数组包含所有必要的详细信息:
$url array contains all necessary details:
Array
(
[scheme] => http
[host] => www.php.net
[path] => /index.html
)
相关文章