0

The Main focus: Remove the protocol and subdomain, but any other non-www subdomain must remain.

Example 1. If the protocol and the standard www subdomain such as http://www.example.net, then the expected result must be: example.net

Example 2. If the protocol and any other non-standard subdomain such as https://jokes.example.net, then the result must be: jokes.example.net

Please, any suggestions.

Carl Barrett
  • 209
  • 5
  • 16
  • Why use preg replace? Maybe str_replace will work? – Alexey Shatrov Feb 26 '17 at 06:52
  • Please provide sample code – Carl Barrett Feb 26 '17 at 06:53
  • http://stackoverflow.com/questions/6336281/php-remove-www-from-url-inside-a-string http://stackoverflow.com/questions/9549866/php-regex-to-remove-http-from-string I think this is answered too many times. :) – Harold Andrino Feb 26 '17 at 06:57
  • The main focus of this question is not to just removing the www from the URL. After reviewing the suggest links they were all unable to answer or address my question and derived any expected results. However, I have edited the question and hope it will clarify this topic. – Carl Barrett Feb 27 '17 at 02:25
  • What about `example.co.uk` and `www.example.co.uk`? – ceejayoz Feb 27 '17 at 02:30
  • That's not a valid URL. Try adding "http://" and any of the two answers below should work. – Carl Barrett Feb 27 '17 at 03:31

2 Answers2

2
$urls="http://www.example.net";
$urls = preg_replace('/(?:https?:\/\/)?(?:www\.)?(.*)\/?$/i', '$1', $urls);
echo $urls; // example.net

$urls="https://jokes.example.net";
$urls = preg_replace('/(?:https?:\/\/)?(?:www\.)?(.*)\/?$/i', '$1', $urls);
echo $urls; // jokes.example.net
B. Desai
  • 16,414
  • 5
  • 26
  • 47
0

You can use preg_replace to check where www is there in url or not.

$url = "https://jokes.example.net/";
$parse = parse_url($url);
$res = $url = preg_replace('#^www\.(.+\.)#i', '$1', $parse['host']);
print_r($res);
prakash tank
  • 1,269
  • 1
  • 9
  • 15
  • This code also works as expected. I totally overlooked parsing the URL, so it's good to see another option. The code below by B. Desai was the closest to my code and I was able to quickly fix it. Thanks for understanding the question from the "get go", that tells me you are also a pro. – Carl Barrett Feb 27 '17 at 02:59