I have a bunch of urls like these.
$urls = array(
'https://site1.com',
'https://www.site2.com',
'http://www.site3.com',
'https://site4.com',
'site5.com',
'www.site6.com',
'www.site7.co.uk',
'site8.tk'
);
I wanted to remove the http, https, :// and www. from these strings so that the output will look like these.
$urls = array(
'site1.com',
'site2.com',
'site3.com',
'site4.com',
'site5.com',
'site6.com',
'site7.co.uk',
'site8.tk'
);
I came up with this solution.
foreach ($urls as $url) {
$pattern = '/(http[s]?:\/\/)?(www\.)?/i';
$replace = "";
echo "before: $url after: ".preg_replace('/\/$/', '', preg_replace($pattern, $replace, $url))."\n";
}
I was wondering how I could avoid the second preg_replace. Any ideas?
preg_replace can also take an array, so you don’t even need the loop. You can do this with a one liner: