DOM拡張機能を使用すると、XPathを使用してすべてのimgタグを検索し、それらを置き換えることができます
。以下も参照してください。
例えば
<?php
// closure/lambda, php 5.3+ only
$convert = function($src) {
return '---'.$src.'---';
};
$doc = new DOMDocument;
$doc->loadhtml(getHTML());
echo "before: ", $doc->savehtml(), "\n\n";
foo($doc, $convert);
echo "after: ", $doc->savehtml(), "\n\n";
function foo(DOMDocument $doc, $fn) {
$xpath = new DOMXPath($doc);
$imgs = array();
foreach( $xpath->query('/html/body//img') as $n ) {
$imgs[] = $n;
}
foreach($imgs as $n) {
$txt = $fn($n->getAttribute('src'));
$div = $doc->createElement('div', $txt);
$n->parentNode->replaceChild($div, $n);
}
}
function getHTML() {
return '<html><head><title>...</title></head><body>
<p>lorem ipsum <img src="a.jpg" alt="img#1"/></p>
<p>dolor sit amet<img src="b.jpg" alt="img#2"/></p>
<div><div><div><img src="c.jpg" alt="img#3" /></div></div></div>
</body></html>';
}
プリント
before: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><title>...</title></head><body>
<p>lorem ipsum <img src="a.jpg" alt="img#1"></p>
<p>dolor sit amet<img src="b.jpg" alt="img#2"></p>
<div><div><div><img src="c.jpg" alt="img#3"></div></div></div>
</body></html>
after: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><title>...</title></head><body>
<p>lorem ipsum <div>---a.jpg---</div></p>
<p>dolor sit amet<div>---b.jpg---</div></p>
<div><div><div><div>---c.jpg---</div></div></div></div>
</body></html>