PHP: How to replace dynamic src of an image?

Are you working with PHP and looking for how to replace dynamic src of an image? in PHP?

Let me tell you how to do this in PHP.

How to replace image src?

Let us assume we are extracting product details from database and saving it in a variable named $product_description.

//a PHP variable that contains HTML string with images in it

Let say the above variable has 2 products with images and it return HTML something like the following:

<title>How to replace src of an image?</title>


<span>Product #1</span>
<a href="#">
<figure><img src="image/catalog/image1.jpg"></figure>

<span>Product #1</span>
<a href="#">
<figure><img src="image/catalog/image1.jpg"></figure>


There can be many images for a product in its description but I have just used 2 images in my example.

We will be doing the following 2 steps:

1- Replace src of every image with
for all images in HTML string.

2- Add a new attribute data-src that will be like
for the image number 1 and
for the image number 2.


How to assign the original src value of each image to its dynamically added data-src attribute ?

Here are the 2 possible solutions for this problem:

Solution #1

$doc = new DOMDocument();
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
 $old_src = $tag->getAttribute('src');
 $new_src_url = 'image/catalog/blank.gif';
 $tag->setAttribute('src', $new_src_url);
 $tag->setAttribute('data-src', $old_src);
$product_description = $doc->saveHTML();

Solution #2

$product_description=preg_replace('(src="(.*?)")','src="image/catalog/blank.gif" data-echo="$1"',$product_description);

The solution #2 is more efficient.

Happy Coding!

Liked it? Please Share:

Add a Comment

Your email address will not be published. Required fields are marked *