note 79652 deleted from function.preg-match by felipe

From: Date: Sun, 23 Mar 2008 22:56:05 +0000
Subject: note 79652 deleted from function.preg-match by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137377@lists.php.net to get a copy of this message
Note Submitter: noel at HATESPAM dot noelswanson dot com ---- Not quite sure why no one has posted this before (unless I missed it somewhere) but "Example 1531. Getting the domain name out of a URL" clearly doesn't work for domains such as .co.uk. Here is a simple improvement that does a much better job at extracting a domain from a URL (though not perfect). It assumes the following: country code TLD's have two letters (eg .uk, .jp, .au), and their subdomains have two or three letters, (eg .gov.uk, .co.uk). These are parsed in three parts. Anything else is parsed in two parts. Hope it helps! Noel <?php function extract_domain($url){ preg_match('@^(?:http://)?([^/]+)@i', $url, $matches); $host = $matches[1]; // get last three segments of host name if country code TLD with sub domain, eg .co.uk preg_match('/[^.]+\.[^.]{2,3}\.[^.]{2}$/', $host, $matches); if (empty($matches)) { // get last two segments of host name if generic TLD preg_match('/[^.]+\.[^.]+$/', $host, $matches); } return $matches[0]; } ?>

« previous php.notes (#137377) next »