当前位置:Gxlcms > PHP教程 > php正则表达式匹配URL中的域名

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

时间:2021-07-01 10:21:17 帮助过:20人阅读

  1. $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';

  2. $url = 'http://www.php.com/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.com
  11. $4 = www.php.com
  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.com/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.com

人气教程排行