ItSolutionStuff.com

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

By Hardik Savani • May 14, 2024
PHP

I am going to show you example of php replace image src om html string. I’m going to show you about How to replace image src in a dynamic HTML string in php. i would like to share with you php replace img tag in string. i explained simply step by step replace image src in html string php.

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.

index.php

<?php

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

$doc->loadHTML($htmlString);

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

print($htmlString);

output:

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

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

PHP Create Directory If It Doesn't Exist Example

Read Now →
ā˜…

How to Get Difference Between Two Dates in PHP?

Read Now →
ā˜…

Codeigniter Curl Post Request with Parameters Example

Read Now →
ā˜…

How to Convert String to Date in PHP?

Read Now →
ā˜…

How to Convert Array to JSON in PHP?

Read Now →
ā˜…

How to Get Single Row from Database in Codeigniter?

Read Now →
ā˜…

PHP MySQL Login with Google Account Example

Read Now →
ā˜…

Tags Input with Autocomplete using jQuery and PHP Example

Read Now →
ā˜…

How to Find Day Name from Specific Date in PHP?

Read Now →
ā˜…

How to Remove Null Values from Array in PHP?

Read Now →