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

WBOY
发布: 2016-07-25 09:07:27
原创
2106 人浏览过
  1. $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';

  2. $url = 'http://www.php.net/pub/ietf/uri/#Related';
  3. $url = trim($url);
  4. preg_match_all($search, $url ,$rr);
  5. printf("

    输出URL数据为:

    %s
    登录后复制
    \n",var_export( $rr ,TRUE));
  6. /*

  7. 各分组如下
  8. $1 = http:
  9. $2 = http
  10. $3 = //www.php.net
  11. $4 = www.php.net
  12. $5 = /pub/ietf/uri/
  13. $6 =
  14. $7 =
  15. $8 = #Related
  16. $9 = Related
  17. */
  18. ?>
复制代码

这里提供另一个简洁的代码:

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

执行后输出:domain name is: php.net



来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!