Extracting a domain name with PHP and Regular Expressions

As most of your know, regular expressions can be a nightmare if you don’t know much about the subject. Here is a quick tutorial on how you can extract the domain name from any URL using regular expressions and PHP. This includes http:// and https:// domain names.

 
<?php 	
$link1 = "http://nickduncan.co.za/";
$link2 = "http://nickduncan.co.za";
$link3 = "http://www.nickduncan.co.za/";
$link4 = "http://www.nickduncan.co.za";
 
$link5 = "https://nickduncan.co.za/";
$link6 = "https://nickduncan.co.za";
$link7 = "https://www.nickduncan.co.za/";
$link8 = "https://www.nickduncan.co.za";
 
$link9 = "http://www.nickduncan.co.za/index.php";
$link10 = "http://www.nickduncan.co.za/index.php?id=34&that=this";
$link11 = "http://nickduncan.co.za/php-header-include-%E2%80%93-saving-development-time/";
 
echo return_domain($link1)." - ".$link1;
echo "<br />".return_domain($link2)." - ".$link2;
echo "<br />".return_domain($link3)." - ".$link3;
echo "<br />".return_domain($link4)." - ".$link4;
echo "<br />".return_domain($link5)." - ".$link5;
echo "<br />".return_domain($link6)." - ".$link6;
echo "<br />".return_domain($link7)." - ".$link7;
echo "<br />".return_domain($link8)." - ".$link8;
echo "<br />".return_domain($link9)." - ".$link9;
echo "<br />".return_domain($link10)." - ".$link10;
echo "<br />".return_domain($link11)." - ".$link11;
 
 
function return_domain($link) {
    $domain = preg_match('@^(?:https?://)?([^/]+)@i', $link, $matches);
    return $matches[1];
}
?>

Another easy method is to use the PHP function called parse_url which returns certain elements of a URI that you choose. For examples on this function, consult the PHP manual which has more than enough examples.