Php preg_replace swap image src

-1

I would like to know how to add the url of the site in front of the existing src of all the 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">

To:

<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?

    
asked by anonymous 01.08.2015 / 20:33

2 answers

1

I do not know if it would help you, but you can try it in the following way, maybe it would be a solution ... As I did not quite understand how you would like it, and if url comes from some string but if try this:

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

If you give print_r to $str_image it 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.br/teste.jpg'>
    
01.08.2015 / 21:47
1

You do not 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);
    
01.08.2015 / 22:26