Reputation: 2547
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!
Upvotes: 0
Views: 227
Reputation: 12174
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();
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();
Upvotes: 2