Reputation: 33946
My current js formula removes http://, https://, www and anything after '/'.
function cleanUrl(url) {
return url.replace(/^(http(s)?:\/\/)?(www\.)?/gi,"");
}
E.G: http://www.google.com/piza returns google.com
How can I do remove everything but the domain in one step but with PHP?
Upvotes: 3
Views: 1565
Reputation: 2096
There is a much easier way ;)
<?php
echo $_SERVER['HTTP_HOST']
?>
Upvotes: -4
Reputation: 197624
You can combine the regex you have (with a little modification) and Use parse_url()
Docs to do the main work:
function cleanUrl($url) {
return preg_replace('/^(www\.)?/i',"", parse_url($url, PHP_URL_HOST));
}
As ceejayoz wrote, you might want to keep www.
as part of the domain name.
Upvotes: 0
Reputation: 967
The function parse_url()
is quite powerful, and the example usage from php.net will shed some light on what kinds of things you can do with it:
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
The above example will output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
Upvotes: 0
Reputation: 1565
You could use preg_replace with your current regex and get the same result: http://php.net/manual/en/function.preg-replace.php
Upvotes: 2
Reputation: 179994
Use parse_url()
.
$domain = parse_url($url, PHP_URL_HOST);
Do note that www.example.com and example.com are technically entirely separate entities that can point at totally different sets of records.
Upvotes: 8