Home  >  Article  >  Backend Development  >  php regular expression to match domain name in URL

php regular expression to match domain name in URL

WBOY
WBOYOriginal
2016-07-25 09:07:272106browse
  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("

    The output URL data is:

     %s
    n",var_export( $rr ,TRUE));

  6. /*

  7. Each group is as follows
  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. ?> ;

Copy the code

Another concise code is provided here:

  1. // Get the hostname from the URL
  2. preg_match("/^(http ://)?([^/]+)/i", "http://www.php.net/index.html", $matches);
  3. $host = $matches[2];
  4. // from Get the last two segments from the host name
  5. preg_match("/[^./]+.[^./]+$/", $host, $matches);
  6. echo "domain name is: {$matches[0]} n";
  7. ?>
Copy the code

Output after execution: domain name is: php.net



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn