Page 1 of 1

Regex that matches domain/subdomain

Posted: Sun Jun 06, 2004 1:24 pm
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:

Posted: Mon Jun 07, 2004 12:59 am
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";
?>

Posted: Mon Jun 07, 2004 11:49 pm
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.

Posted: Sun Jun 13, 2004 9:37 pm
by Rahil
Thanks guys.