Put simply, I need to check if the string in the variable $url is a simple http, if so, replace it with https - but I can't get it to work - any ideas:
$url="http://www.google.com"; // example http url ##
$url_replaced = preg_replace( '#^http://#','https://', $url ); // replace http with https ##
Cheers!
Why not str_replace
?
$url="http://www.google.com"; // example http url ##
$url = str_replace('http://', 'https://', $url );
echo $url;
preg_replace()
is unnecessary here. Just use str_replace()
.
str_replace('http://', 'https://', $url)
You could always create a simple function that returns the link as secure. Much easier if you need to change a lot of links.
function secureLink($url){
$url = str_replace('http://', 'https://', $url );
return $url;
};
Do NOT use str_replace
, as it can happen you will replace string in the middle (if the url is not encoded correctly).
preg_replace("/^http:/i", "https:", $url)
Note the /i
parameter for case insensitive and ^
saying it have to start with this string.
http://sandbox.onlinephpfunctions.com/code/3c3882b4640dad9b6988881c420246193194e37e
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.