How to replace image src in a dynamic HTML string?

Hello dev
Today,i am going to show you a simple example of php replace image src on html string. So now i’m going to show you How to replace image src in a dynamic HTML string by using php. I would like to share with you a basic example of php replace img tag in string. Now i explained it simply step by step replace image dynamic src in html string by using php.

In our project sometime we need to change src in a dynamic html string by using php. That’s i mean that if you store html string into any database and you have to update src path for that string. When you want display in front end side. So here i will give you a very simple example for  replace image src in html string by using php.

Let’ start and see bellow index.php file and output. So you can easily understand about how it works and using in DOM Document.


$htmlString = '<strong>Image One:</strong><br/>
<img src="imageone.png" /><br/>
<strong>Image Two:</strong><br/>
<img src="imagetwo.png" /><br/>
<strong>Image Three:</strong><br/>
<img src="imagethree.png" /><br/>';
$doc = new DOMDocument();
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
   $oldSrc = $tag->getAttribute('src');
   $newScrURL = 'upload/images/'.$oldSrc;
   $tag->setAttribute('src', $newScrURL);
   $tag->setAttribute('data-src', $oldSrc);
$htmlString = $doc->saveHTML();

Read Also : How to disable submit button in jQuery?


<strong>Image One:</strong><br>

<img src="upload/images/imageone.png" data-src="imageone.png"><br>


<strong>Image Two:</strong><br>

<img src="upload/images/imagetwo.png" data-src="imagetwo.png"><br>


<strong>Image Three:</strong><br>

<img src="upload/images/imagethree.png" data-src="imagethree.png"><br>

Read Also : PHP AngularJS CRUD with Search and Pagination Example From Scratch

Hope it will be help you ……….. Also you can follow us on Facebook .


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →