PHP Regex to Remove http:// from string
I have full URLs as strings, but I want to remove the http:// at the beginning of the string to display the URL nicely (ex: www.google.com instead of http://www.google.com)
Can someone help?
Solution 1:
$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com
That will work for both http://
and https://
Solution 2:
You don't need regular expression at all. Use str_replace instead.
str_replace('http://', '', $subject);
str_replace('https://', '', $subject);
Combined into a single operation as follows:
str_replace(array('http://','https://'), '', $urlString);
Solution 3:
Better use this:
$url = parse_url($url);
$url = $url['host'];
echo $url;
Simpler and works for http://
https://
ftp://
and almost all prefixes.
Solution 4:
Why not use parse_url
instead?
Solution 5:
To remove http://domain ( or https ) and to get the path:
$str = preg_replace('#^https?\:\/\/([\w*\.]*)#', '', $str);
echo $str;