Php preg_replace replace src image

Asked

Viewed 304 times

-1

I would like to know how to add the site url in front of the existing src of all images of an example string:

<img src="images/teste.jpg" border="0" width="486" height="370" style="margin: 5px; float: left;" />
<img src="images/teste2.jpg">

for:

<img src="www.meusite.com/images/teste.jpg" border="0" width="486" height="370" style="margin: 5px; float: left;" />
<img src="www.meusite.com/images/teste2.jpg">

What regular expression can I use for this?

  • It is not good for you to do this in time of execution, because it will fall a lot. Try creating a URL_IMG constant with the site address, then along with the editing tool replace <img src=" with <img src="<?= URL_IMG ? > I think this will revolve.

  • The problem is that I only have a string with html, I need to change on top of the string, because I am building a service.

  • This img src comes from some string?

2 answers

1


I don’t know if it would help you, but you can try it this way, maybe it would be a solution... As I didn’t quite understand how you would like it, and if the url comes from some string but if you come, you can try it like this:

$img = "<img src='teste.jpg' border='0'>";
$add_url = "http://www.google.com";
$str_image = explode("'", $img);
$new_image = "<img src='{$add_url}/{$str_image[1]}'>";
echo $new_image;

If you give a print_r in the $str_image would return the following:

Array
(
    [0] => <img src=
    [1] => teste.jpg
    [2] =>  border=
    [3] => 0
    [4] => >
)

And with echo in $new_image:

<img src='http://www.google.com/teste.jpg'>

1

You don’t even need preg_replace.

$html = '<img src="images/teste.jpg" border="0" width="486" height="370" style="margin: 5px; float: left;" /><img src="images/teste2.jpg">';

echo str_replace('<img src="','<img src="http://www.meusite.com/',$html);

Browser other questions tagged

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