PHP Replace Img Src from string Example

This simple article demonstrates of php replace img tag in string. if you want to see example of replace image src in html string php then you are a right place. you will learn replace image src in html using php. i would like to show you php replace image src om html string. Alright, let’s dive into the steps.

Sometime we need to change src in a dynamic html string with php. i mean if you store html string into database and you have to update src path for that string when you display in front end side. so here i will give you very simple example of replace image src in html string using php.

Let' see bellow index.php file and output so you can easily understand how it works using DOMDocument.



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



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

I hope it can help you...

October 16, 2020 | Category : Other

Blog Search