Preg_replace http with https

Simply put, I need to check if the string in the $ url variable is 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 ##

Hooray!

+3
source share
3 answers

Why not str_replace?

$url="http://www.google.com"; // example http url ##
$url = str_replace('http://', 'https://', $url ); 
echo $url;
+12
source

preg_replace()not required here. Just use it str_replace().

str_replace('http://', 'https://', $url)
+3
source

You can always create a simple function that returns the link as safe. Much easier if you need to change many links.

function secureLink($url){

$url = str_replace('http://', 'https://', $url ); 
return $url;
};
+1
source

All Articles