Replace specific <font> tag with <span> using DOM manipulation in PHP -
i'm trying replace tags tags using domdocument in php , tests passed. i'm sure there other scenarios i'm forgetting, now, i'm missing one:
original:
<p><font color="#ff0000">before <font color="#00ff00">before <font color="#0000ff">val</font> after</font> after</font></p>
result:
<p><span style="color: #ff0000">before before val after after</span></p>
the php code this:
$html = '<p><font color="#ff0000">before <font color="#00ff00">before <font color="#0000ff">val</font> after</font> after</font></p>'; $dom = new domdocument(); $dom->loadhtml($html); foreach($dom->getelementsbytagname('font') $node) { $font_nodes[] = $node; } //$font_nodes = array_reverse($font_nodes); foreach($font_nodes $font) { $a_style = array_filter(explode(';', $font->getattribute('style'))); if($a_color = $font->getattribute('color')) { $a_style[] = 'color: '.$a_color; } $span = $dom->createelement('span', $font->nodevalue); $span->setattribute('style', implode('; ', $a_style)); $font->parentnode->replacechild($span, $font); } echo preg_replace("#(<!doctype.+|<\/?html>|<\/?body>)#", '', $dom->savehtml());
i thought getelementsbytagname
culprit since loading nodes in order, tried start deepest tag reversing array, didn't work line commented.
p.s: in case you're wondering why first loop needed save nodes , loop them again, please read this: http://robrosenbaum.com/php/domnodelist-gotchas/
this works. tested it. :-)
replace line:
$span = $dom->createelement('span', $font->nodevalue);
with this:
$span = $dom->createelement('span'); $children = array(); foreach ($font->childnodes $child) $children[] = $child; foreach ($children $child) $span->appendchild($child);
Comments
Post a Comment