joozh 发表于 2015-8-30 07:34:01

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

  在PHP的官网上看到的parse_url()函数的替代。结果和parse_url()函数差不多,是使用正则实现的,看到好就转过来。
  原文:http://www.php.net/parse_url#104958
  
  我就不翻译了,它可以解析URI
  URI 是 Web上可用的每种资源 - HTML文档、图像、视频片段、程序等 - 由一个通用资源标志符(Uniform Resource Identifier, 简称"URI")进行定位。
  对就分组:
        ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            34          5       67      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;
// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches}\n";
?>
  执行后输出:domain name is: php.net
页: [1]
查看完整版本: PHP正则表达式匹配URL中的域名