PHP Regular expression matches the domain name in the URL

Source: Internet
Author: User
Tags php regular expression
    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. The groupings are as follows
    8. $ = http:
    9. $ = http
    10. $ $ =//www.php.net
    11. $4 = Www.php.net
    12. $ $ =/pub/ietf/uri/
    13. $6 =
    14. $7 =
    15. $8 = #Related
    16. $9 = Related
    17. */
    18. ?>

Copy Code

Here's another neat code:

    1. Get host name from URL
    2. Preg_match ("/^ (http:\/\/)?" ( [^\/]+)/I "," http://www.php.net/index.html ", $matches);
    3. $host = $matches [2];
    4. Get the next two paragraphs from the hostname
    5. Preg_match ("/[^\.\/]+\.[ ^\.\/]+$/", $host, $matches);
    6. echo "Domain name is: {$matches [0]}\n";
    7. ?>
Copy Code

Post-execution output: domain name is:php.net

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.