【发布时间】:2012-10-24 13:04:43
【问题描述】:
我有这个 html 片段:
<font color="#ff0000">Lorem <font size="4">ipsum dolor</font> sit amet</font>
我想使用 DOMDocument 将每个 font 标记替换为 span。
那是我的 atm 函数:
$fonts = $xPath->query('//font');
foreach($fonts as $font){
$style = '';
$newFont = $dom->createElement('span',$font->nodeValue);
if($font->hasAttribute('size')){
$size = $font->getAttribute('size');
$style.='font-size:'.round($size/2,1).'em; ';
}
if($font->hasAttribute('color')){
$style.='color:'.$font->getAttribute('color').'; ';
}
if($style!='') $newFont->setAttribute('style',$style);
$font->parentNode->replaceChild($newFont,$font);
}
我期望这个输出:
<span style="color:#ff0000; ">Lorem <span style="font-size:2em;">ipsum etc..
但我明白了:
<span style="color:#ff0000; ">Lorem ipsum dolor sit amet</span>
为什么?
我猜这是因为$font->parentNode->replaceChild($newFont,$font); 以某种方式仅用它的文本值替换了外部跨度......或者这个查询$xPath->query('//font') 是错误的。我喜欢有经验的建议...谢谢
【问题讨论】:
-
为什么不直接使用正则表达式?
-
@rekire 我已经这样做了很长时间,但我正在尝试切换到 DOMDocument / html5lib ...codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
-
我知道html标签对不能用正则表达式替换,但是简单的关闭字体标签在每种情况下都可以用关闭跨度替换不是吗?
-
yup @rekire 即使使用 str_replace 和 preg_match 我也可以处理这种特殊情况......我只是想了解 DOMDocument 的工作原理,但我迷失在官方文档中;-)
标签: php domdocument domxpath