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
$product_description=html_entity_decode($product_description,ENT_QUOTES,'UTF-8');


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

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

<body>

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

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

</body>
</html>


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
src=”image/catalog/blank.gif”
for all images in HTML string.

2- Add a new attribute data-src that will be like
data-src=”/image/catalog/image1.jpg”
for the image number 1 and
data-src=”/image/catalog/image2.jpg”
for the image number 2.

Problem:


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

$product_description=html_entity_decode($product_description,ENT_QUOTES,'UTF-8');
 
$doc = new DOMDocument();
$doc->loadHTML($product_description);
$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=html_entity_decode($product_description,ENT_QUOTES,'UTF-8');
 
$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 *