0

Find and replace Img tag in a string via php ?

$source = "<img src='source.jpg'>";
$dest = '<div id="pf1" class="pf w0 h0" data-page-no="1">
<div class="pc pc1 w0 h0">
  <img class="bi x0 y0 w0 h0" alt="" src="../images/cover.jpg"/>
</div>';

I want to replace that $source image in $dest image ..

Aksen P
  • 4,564
  • 3
  • 14
  • 27

1 Answers1

0

You can use preg_replace function, 2 of 3 arguments you already have, the pattern could be like '/<img(.*?)\/>/':

$find = '/<img(.*?)\/>/';
$source = '<img src="source.jpg">';
$dest = '<div id="pf1" class="pf w0 h0" data-page-no="1">
<div class="pc pc1 w0 h0">
  <img class="bi x0 y0 w0 h0" alt="" src="../images/cover.jpg"/>
</div>';

echo preg_replace($find, $source, $dest);  

Output will be:

<div id="pf1" class="pf w0 h0" data-page-no="1">
<div class="pc pc1 w0 h0">
  <img src="source.jpg">
</div>

Working demo

Aksen P
  • 4,564
  • 3
  • 14
  • 27
  • It is generally not recommended to use regex's to manipulate HTML as the chances of it breaking are quite high. – Nigel Ren Nov 21 '19 at 07:42
  • @NigelRen, perhaps, but in case of using a little parts of it - chances are much less. – Aksen P Nov 21 '19 at 07:44
  • Difficulties become when this is just a small part of a full web page and the same code is used, then people start using it for other tags and the chances increase. – Nigel Ren Nov 21 '19 at 07:46
  • @NigelRen, have had read an opinion about RegEx in your "marked" post, yeap, need to be sure how does manipulation affects on your HTML during of using it. That's should be a rule for eachone who use it. Honestly, I'm never using this in my projects. I don't like render HTML via PHP at all. – Aksen P Nov 21 '19 at 07:52