Preg_match:在一个表达式中获取 url 的最后两个域段


Preg_match: get last two domain segments from url in one expression

有一个关于如何通过两个步骤获取最后两个域段 php.net 示例:

    <?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]}'n";
/* Output is php.net */
?>

但是,我怎样才能一步到位,只使用一个preg_match表达式呢?

这段代码:

$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数组中,您可以轻松提取主机名的任何部分。

更新:

print_r($url);

$url数组包含所有必要的详细信息:

Array
(
    [scheme] => http
    [host] => www.php.net
    [path] => /index.html
)