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

查看:98
本文介绍了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]}\n";

/* Output is php.net */

?>

但是,如何只使用一个preg_match表达式呢? b $ b

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跟他们。从生成的$令牌数组,您可以轻松地提取主机名的任何部分。

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天全站免登陆