您的位置:首页 > 编程语言 > PHP开发

PHP正则表达式匹配URL中的域名

2012-06-13 18:31 405 查看
在PHP的官网上看到的parse_url()函数的替代。结果和parse_url()函数差不多,是使用正则实现的,看到好就转过来。

原文:http://www.php.net/parse_url#104958

我就不翻译了,它可以解析URI

URI 是 Web上可用的每种资源 - HTML文档、图像、视频片段、程序等 - 由一个通用资源标志符(Uniform Resource Identifier, 简称"URI")进行定位。

对就分组:

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
12 3 4 5 6 7 8 9

PHP 测试:

<?php
$search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
$url = 'http://www.php.net/pub/ietf/uri/#Related';
$url = trim($url);
preg_match_all($search, $url ,$rr);
printf("<p>输出URL数据为:</p><pre>%s</pre>\n",var_export( $rr ,TRUE));

/*
各分组如下
$1 = http:
$2 = http
$3 = //www.php.net
$4 = www.php.net
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related
*/
?>


百度上看到另外一块简洁的代码:

<?php
// 从 URL 中取得主机名
preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>


执行后输出:domain name is: php.net
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: