3

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!

4 Answers 4

16

Why not str_replace ?

$url="http://www.google.com"; // example http url ##
$url = str_replace('http://', 'https://', $url ); 
echo $url;
Sign up to request clarification or add additional context in comments.

2 Comments

you both answered at the same time.. so Karo get's the points as he / she has less..
Just be careful the URL doesn't contain a query param with another url in it. For example: echo str_replace('http://', 'https://', 'http://foo.com?redirect=http://bar.com'); // https://foo.com?redirect=https://bar.com
3

preg_replace() is unnecessary here. Just use str_replace().

str_replace('http://', 'https://', $url)

Comments

2

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

Comments

1

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.