20

Currently I am using parse_url, however the host item of the array also includes the 'WWW' part which I do not want. How would I go about removing this?

$parse = parse_url($url);
print_r($parse);
$url = $parse['host'] . $parse['path'];
echo $url;
ritch
  • 1,760
  • 14
  • 37
  • 65

3 Answers3

34
$url = preg_replace('#^www\.(.+\.)#i', '$1', $parse['host']) . $parse['path'];

This won't remove the www in www.com, but www.www.com results in www.com.

Floern
  • 33,559
  • 24
  • 104
  • 119
  • your solution is good, but it miss the case like www.www.test.com. updated version - preg_replace('#^(?:www\.)+(.+\.)#i', '$1', $domain); – Sergey Korzhov Feb 03 '22 at 10:55
11
preg_replace('#^(http(s)?://)?w{3}\.#', '$1', $url);

if you don't need a protocol prefix, leave the second parameter empty

Empty
  • 457
  • 2
  • 6
  • 1
    new version: preg_replace('#^(http(s)?://)?w{3}\.(\w+\.\w+)#', '$1$3', $url); Remove $1 for skipping protocol – Empty Jun 14 '11 at 00:05
6
$url = preg_replace('/^www\./i', '', $parse['host']) . $parse['path'];
Frank Farmer
  • 38,246
  • 12
  • 71
  • 89