preg_replace to change image src

Asked

Viewed 85 times

0

I have several news registered in a database, many of them, have images, that point directly to my site.

Only they have http and as I have now installed SSL on my site, I need them to stay with https.

I don’t want to change anything in the database, so I need a preg_replace that changes from http to https, only tags in the src attribute.

This does not apply to links, only images...

Someone can help me?

3 answers

0

<?php

$re = '/([^<img src=\'"]+):/';

$str = '<img src="http://www.google.com"> <img src=\'http://www.google.com\'>';

preg_match_all($re, $str, $matches);

$str = preg_replace($re, 'https', $str);

print_r($str);
  • But then it will take out all src, I want to keep the value inside src and change only http.

0

You can make a simple replace by replacing the http://www.domain.com.br by your url.

$str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        <img src="http://www.domain.com.br/imagem.jpeg">
        <img src="http://www.domain.com.br/imagem.jpeg">';


echo str_replace( 'http://www.domain.com.br' , 'https://www.domain.com.br' , $str );
  • I can’t, because there are external links inside this content, and that would change theirs too.

  • You will change only your links

0

example - ideone

$str = 'Bla bla bla
<img src="http://www.seudominio.com/image1.jpeg">
<img src="http://www.seudominio.com/image2.jpeg">
<a href="http://www.seudominio.com/">http://www.seudominio.com/</a>';

echo str_replace( '<img src="http' , '<img src="https' , $str );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.