regular expressions in php question

mesam

New member
Feb 28, 2008
128
2
0
Anyone mind helping out with this? I currently use this string in php to remove the "www." and grab a domain name:

$domain = str_replace("www.","", $_SERVER['HTTP_HOST']);

I would like to be able to grab just the domain, even if it's not "www." - for example abc.domain.com or 1ns45.domain.com, etc. Basically just grab everything after the first period. I appreciate any help on this.
 


Code:
<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
    $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
    $pos = $strpos($haystack, $needle);
    if (is_int($pos)) {
        return substr($haystack, $pos + strlen($needle));
    }

    return $pos;
}



$thestring = 'blah.wickedfire.com';
$domain = strstr_after($thestring, '.');


echo $domain; 

?>
 
What if it has two periods before the domain name?
Best to look from the right to the left and grab everything after the second period from the right.
Just sayin..
 
If you are just starting with a domain and not a full URL, taking into account that a domain may have multiple sub domains ("http://pitchers.tigers.baseball.sport.com"), and you just want the last two elements; domain and tld.

So, something like this:
list($domain, $tld) = array_slice(explode('.', $url), -2, 2);
 
The regex:
Code:
$domain = preg_replace("/^([a-z0-9]\.)*([a-z0-9]+\.[a-z]{2,4})$/", '\2', $_SERVER['host']);
I did not test this, I wrote it by hand, it might not work YMMV, etc, but you asked for a regex solution :)
Hit me up on AIM if you decide to use this and it doesn't work; I'll gladly fix/debug it with ya.

EDIT:
What worthless asshole posts regex to a forum without even seeing if it works?
This one, right here!
Working code, tested on one of our sites, will give $domain = "blah.com" for any subdomain of blah.com (or http://blah.com itself):
Code:
$domain = preg_replace("/^([a-z0-9]+\\.)*([a-z0-9]+\\.[a-z]{2,4})$/i", '\2', $_SERVER['HTTP_HOST']);
 
Maybe this?

Code:
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.domain.com/yadayada.html", $matches);
$host = $matches[1];

Course throw a (www.)? in there after the http:// check to check against that and make it just get the domain (be it subdomain or non-www domain).
 
Thank you all very much - I really appreciate the help. Went with Uplinked's option, mainly because it seemed the quickest to implement. Thus far it's working perfectly. Tried to +Rep all, but ran out...