Maison  >  Article  >  développement back-end  >  php正则表达式匹配URL中的域名

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

WBOY
WBOYoriginal
2016-07-25 09:07:272106parcourir
  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



Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn