[SOLVED] Regex that matches domain/subdomain

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Rahil
Forum Newbie
Posts: 17
Joined: Sun Feb 15, 2004 2:24 pm
Location: Toronto, Ontario, Canada

Regex that matches domain/subdomain

Post by Rahil »

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. :lol:
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

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";
?>
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

Could also try this one:

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);
?>
output:

Code: Select all

Array
(
    &#1111;0] =&gt; http://www2.smarty.php.net/index.php
    &#1111;1] =&gt; http://
    &#1111;2] =&gt; http
    &#1111;3] =&gt; www2.
    &#1111;4] =&gt; smarty.
    &#1111;5] =&gt; smarty
    &#1111;6] =&gt; php.net
    &#1111;7] =&gt; /index.php
)
-- Scorphus.
Rahil
Forum Newbie
Posts: 17
Joined: Sun Feb 15, 2004 2:24 pm
Location: Toronto, Ontario, Canada

Post by Rahil »

Thanks guys.
Post Reply