PHP uses regular expression matching to obtain the domain name in the URL

Source: Internet
Author: User

The parse_url () function is available on the PHP official website. The result is similar to the parse_url () function, which is implemented using regular expressions.

URI is the type of resources available on the Web-HTML documents, images, video clips, programs, etc.-are located by an Uniform Resource Identifier ("URI. Object group:

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?12            3  4          5       6  7        8 9

The test code is as follows:

<? Php $ search = '~ ^ ([^ :/? #] + ):)? (// ([^ /? #] *)? ([^? #] *) (\? ([^ #] *)? (#(.*))?~ I '; $ url = 'HTTP: // www.bkjia.com/pub/ietf/uri/?gonn'?#url = trim ($ url); preg_match_all ($ search, $ url, $ rr ); printf ("<p> output URL data: </p> <pre> % s </pre> \ n", var_export ($ rr, TRUE )); /* the groups are as follows: $1 = http: $2 = http $3 = // www.bkjia.com $4 = www.bkjia.com $5 =/pub/ietf/uri/$6 = <undefined> $7 = <undefined> $8 = # gonn $9 = Gonn */?>

The above regular expression can get any part of the URL. The following code is simpler:

<? Php // obtain the host name preg_match ("/^ (http: \/) from the URL :\/\/)? ([^ \/] +)/I "," http://www.bkjia.com/index.html ", $ matches); $ host = $ matches [2]; // obtain the preg_match ("/[^ \. \/] + \. [^ \. \/] + $/", $ host, $ matches); echo" domain name is: {$ matches [0]} \ n ";?>

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.