Preg_match:在一个表达式中从 url 中获取最后两个域段 [英] Preg_match: get last two domain segments from url in one expression

查看:26
本文介绍了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
)

这篇关于Preg_match:在一个表达式中从 url 中获取最后两个域段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆