note 79652 added to function.preg-match
| From: | noel at HATESPAM dot noelswanson dot com | Date: | Thu, 06 Dec 2007 19:08:07 +0000 |
| Subject: | note 79652 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132898@lists.php.net to get a copy of this message | ||
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];
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 75.153.60.67
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/79652
Del: integrated -- https://master.php.net/note/delete/79652/integrated
Del: useless -- https://master.php.net/note/delete/79652/useless
Del: bad code -- https://master.php.net/note/delete/79652/bad+code
Del: spam -- https://master.php.net/note/delete/79652/spam
Del: non-english -- https://master.php.net/note/delete/79652/non-english
Del: in docs -- https://master.php.net/note/delete/79652/in+docs
Del: other reasons-- https://master.php.net/note/delete/79652
Reject -- https://master.php.net/note/reject/79652
Search -- https://master.php.net/manage/user-notes.php