[SOLVED] Regex that matches domain/subdomain
Moderator: General Moderators
Regex that matches domain/subdomain
Does anyone have a regex that will match a domain, and another regex that will match a subdomain? I've tried searching google, and many PHP websites/forums but found nothing. Any help is appreciated. 
- scorphus
- Forum Regular
- Posts: 589
- Joined: Fri May 09, 2003 11:53 pm
- Location: Belo Horizonte, Brazil
- Contact:
The PHP Manual[/url] at [url=http://www.php.net/preg_match]preg_match reference page[/url] on [url=http://www.php.net/preg_match#AEN99750]Example 3. Getting the domain name out of a URL wrote:Code: Select all
<?php // get host name from URL preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches); $host = $matches[2]; // get last two segments of host name preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches); echo "domain name is: {$matches[0]}\n"; ?>
- scorphus
- Forum Regular
- Posts: 589
- Joined: Fri May 09, 2003 11:53 pm
- Location: Belo Horizonte, Brazil
- Contact:
Could also try this one:
output:
-- Scorphus.
Code: Select all
<?php
$url = 'http://www2.smarty.php.net/index.php';
$regexp = '/^(((?:ht|f)tp):\/\/)?(www?[0-9]*?\.)?(([a-zA-Z0-9][[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]]?)\.)?([a-zA-Z0-9][[[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]]?\.]*[a-zA-Z]{2,6})(\/.*)?$/';
preg_match($regexp, $url, $matches);
print_r($matches);
?>Code: Select all
Array
(
ї0] => http://www2.smarty.php.net/index.php
ї1] => http://
ї2] => http
ї3] => www2.
ї4] => smarty.
ї5] => smarty
ї6] => php.net
ї7] => /index.php
)