我正在尝试使用 PHP 中的 DOMDocument 标签替换所有标签,并且几乎所有测试都通过了。我确信还有其他场景我忘记了,但现在我只错过了一个:
原件:
<p><font color="#ff0000">BEFORE <font color="#00ff00">BEFORE <font color="#0000ff">VAL</font> AFTER</font> AFTER</font></p>
结果:
<p><span style="color: #ff0000">BEFORE BEFORE VAL AFTER AFTER</span></p>
PHP 代码:
$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') as $node) {
$font_nodes[] = $node;
}
//$font_nodes = array_reverse($font_nodes);
foreach($font_nodes as $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());
我认为 getElementsByTagName
是罪魁祸首,因为它按顺序加载节点,所以我尝试通过反转数组从最深的标签开始,但这不起作用,所以该行是发表评论。
P.S:如果您想知道为什么需要第一个循环来保存所有节点并再次循环它们,请阅读以下内容:http://robrosenbaum.com/php/domnodelist-gotchas/
最佳答案
这有效。我测试过。 :-)
替换行:
$span = $dom->createElement('span', $font->nodeValue);
这样:
$span = $dom->createElement('span');
$children = array();
foreach ($font->childNodes as $child) $children[] = $child;
foreach ($children as $child) $span->appendChild($child);
关于php - 在 PHP 中使用 DOM 操作将特定的 <font> 标记替换为 <span>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048314/