How to replace image src in a dynamic HTML string with PHP

In this PHP Lesson, you will learn how to replace image src attribute from a dynamic HTML string using PHP methods.

Let’s assume we get products description from database and we have to decode any HTML tags from that description and display on front-end. See the following PHP code:


It will return HTML something like this:

<strong>1-Product Name:</strong>
<a href="linkURL">
<figure><img src="image/catalog/image1.jpg"></figure>

<strong>2-Product Name:</strong>
<a href="linkURL">
<figure><img src="image/catalog/image2.jpg"></figure>

There could be so many images in the product description. I have added just 2 in my example.


1-Replace src of every image with src=”image/catalog/blank.gif” for all images.
2-Add a new attribute data-src that will be like data-src=”” for the image number 1 and data-src=”” for the image number 2.

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

Also Check: How to remove duplicate values from arrays in PHP.


The first solution to replace image src from dynamic HTML string using PHP is:


$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);

$data['description'] = $doc->saveHTML();


Here is another solution which is more simple and efficient:

For this you have to use a built-in function of PHP which is preg_replace.
Capture the text you want using (parentheses), then reference to that group 1 using $1 or 1 in regular expression.


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

I hope it may help someone.

Happy coding!!!

Sharing is caring. Please Share!