0

I've a string like this:

$url = '<p>IMAGE 1:</p><img src="http://example.com/image1.jpg"><br><p>IMAGE 2:</p><img src="http://www.example.com/image2.jpg"><br><p>IMAGE 3:</p><img src="http://externalsite.com/image3.jpg"><br><p>IMAGE 4:</p><img src="http://www.externalsite.com/image4.jpg">'

example.com is the domain where my webapp is located.

I need:

  1. check if example.com is http or https
  2. if https, replace all http://example.com and http://www.example.com in my string to: https://www.example.com (so not include other domains like externalsite.com)

For first point I can use: $isHttps = !empty($_SERVER['HTTPS']) ? true : false;

For second point i'm not sure how create a preg_replace correctly

Giuseppe Lodi Rizzini
  • 1,045
  • 11
  • 33

1 Answers1

0

I think this is the logic you want. We can search for the following regex pattern:

http://(?:www\.)?example\.com

This would match both http://example.com and http://www.example.com. Then, we can replace with the https version of these URLs.

$url = '<p>IMAGE 1:</p><img src="http://example.com/image1.jpg"><br><p>IMAGE 2:</p><img src="http://www.example.com/image2.jpg"><br><p>IMAGE 3:</p><img src="http://externalsite.com/image3.jpg"><br><p>IMAGE 4:</p><img src="http://www.externalsite.com/image4.jpg">';
$output = preg_replace("/http:\/\/(?:www\.)?example\.com/", "https://www.example.com", $url);
echo $output;

This prints:

<p>IMAGE 1:</p><img src="https://www.example.com/image1.jpg"><br><p>IMAGE 2:</p><img src="https://www.example.com/image2.jpg"><br><p>IMAGE 3:</p><img src="http://externalsite.com/image3.jpg"><br><p>IMAGE 4:</p><img src="http://www.externalsite.com/image4.jpg">
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360