Php regular expression matches the domain name in the URL
$ Search = '~ ^ ([^ :/? #] + ):)? (// ([^ /? #] *)? ([^? #] *) (\? ([^ #] *)? (#(.*))?~ I ';
- $ Url = 'http: // www.php.net/pub/ietf/uri/#related ';
- $ Url = trim ($ url );
- Preg_match_all ($ search, $ url, $ rr );
- Printf ("
The output URL data is: %s \ N ", var_export ($ rr, TRUE ));
/*
- The groups are as follows:
- $1 = http:
- $2 = http
- $3 = // www.php.net
- $4 = www.php.net
- $5 =/pub/ietf/uri/
- $6 =
- $7 =
- $8 = # Related
- $9 = Related
- */
- ?>
Here we provide another concise code:
- // Obtain the host name from the URL
- Preg_match ("/^ (http :\/\/)? ([^ \/] +)/I "," http://www.php.net/index.html ", $ matches );
- $ Host = $ matches [2];
- // Obtain the following two segments from the host name
- Preg_match ("/[^ \. \/] + \. [^ \. \/] + $/", $ host, $ matches );
- Echo "domain name is: {$ matches [0]} \ n ";
- ?>
Output after execution: domain name is: php.net |