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 say 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:

$data['description']=html_entity_decode($product_info['description'],ENT_QUOTES,'UTF-8');

It will return HTML something like this:

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

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


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

Requirements:

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=”http://myproject.com/image/catalog/image1.jpg” for the image number 1 and data-src=”http://myproject.com/image/catalog/image2.jpg” 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.

Solutions:

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

$data['description']=html_entity_decode($product_info['description'],ENT_QUOTES,'UTF-8');

$doc = new DOMDocument();
$doc->loadHTML($data['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);
}

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

Reference: http://php.net/manual/en/domdocument.getelementsbytagname.php

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.

$product_description=html_entity_decode($product_info['description'],ENT_QUOTES,'UTF-8');

$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. Share if you Liked it!

Haroon Ejaz

A Software Engineer, primarily focusing on PHP development with over 3 years experience and a Bachelors degree in Information Technology.