Try this.
function cleanUrl($url) {
/*
// valid url
if(($d = parse_url($url)) !== false) {
return sprintf('%s%s%s',
ltrim($d['host'], 'www.'),
rtrim($d['path']. '/'),
!empty($d['query']) ? '?'.$d['query'] : '');
}
*/
if(strpos($url, 'www.') !== false) {
$url = substr($url, 0, strpos($url, '.', strpos($url, '.')+1));
$array = array('http://' => '', 'https://' => '', '//' => '', 'www.' => '', ' ' => '', ' ' => '');
$url = strtr($url, $array);
return $url;
} else {
$url = substr($url, 0, strpos($url, '.', strpos($url, '.')));
$array = array('http://' => '', 'https://' => '', '//' => '', ' ' => '', ' ' => '');
$url = strtr($url, $array);
return $url;
}
}
I commented out your stuff because it looks to rely on finding certain parts of the URL which kind of doesn’t work because in a URL, there can be more than 1 path.
In the snippet I modified for you, you check to see if the URL contains www.
using strpos. If the string contains www.
, then you find the second period and remove everything after it. Next, with a little combining, you can take the string that you have left and remove the www.
along with http://
, https://
, and //
using an array. You’ll end up with example
. However, if the string doesn’t contain www.
, you go to the second statement and find the first period instead of the second. Then, remove everything after the first period along with http://
, https://
, and //
using an array. Again, you’ll end up with example
.
Hope this helps.
Also, I forgot to tell you to remove all spacing so you end up with
example
instead of
example