0

Say I have an HTML string with multiple occurrences like below:

<img scr1="xxxx.jpg" src="aaaa.jpg" other_attributes="some_values" />

I want to make the "src" attribute to be replaced by the value of the "src1" attributes inside the same tag. (so that in the example it would have src="xxxx.jpg" instead).

How can I achieve this with PHP?

Thanks a lot!

1 Answer 1

2

Using DOMDocument

<?php
$html = '<img scr1="xxxx.jpg" src="aaaa.jpg" other_attributes="some_values" />';

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);

$images = $xpath->query("//img");
foreach ($images as $image) {
    if ($image->hasAttribute('scr1')) {
        $src1 = $image->getAttribute('scr1');
        $image->removeAttribute('scr1');
        $image->setAttribute('src', $src1); 
    }
}

echo $dom->saveHTML();

https://3v4l.org/524Al

Result:

<img src="xxxx.jpg" other_attributes="some_values">

UPDATE

from Why doesn't PHP DOM include slash on self-closing tags:

header('Content-Type: application/xhtml+xml');
echo $dom->saveXML();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! But it's missing the closed tag slash for the img tag. It should end with /> , how can I make this happen?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.