>  기사  >  백엔드 개발  >  php正则表达式匹配URL中的域名

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

WBOY
WBOY원래의
2016-07-25 09:07:272104검색
  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



성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.