我有一个带有HTML标记的DOM对象.我正在尝试替换所有嵌入式标签,如下所示:
<embed allowfullscreen="true" height="200" src="path/to/video/1.flv" width="320"></embed>
Run Code Online (Sandbox Code Playgroud)
使用这样的标签:
<a
href="path/to/video/1.flv"
style="display:block;width:320px;height:200px;"
id="player">
</a>
Run Code Online (Sandbox Code Playgroud)
我很难解决这个问题,我不想为此使用正则表达式.你能救我吗?
编辑:
这是我到目前为止:
// DOM initialized above, not important
foreach ($dom->getElementsByTagName('embed') as $e) {
$path = $e->getAttribute('src');
$width = $e->getAttribute('width') . 'px';
$height = $e->getAttribute('height') . 'px';
$a = $dom->createElement('a', '');
$a->setAttribute('href', $path);
$a->setAttribute('style', "display:block;width:$width;height:$height;");
$a->setAttribute('id', 'player');
$dom->replaceChild($e, $a); // this line doesn't work
}
Run Code Online (Sandbox Code Playgroud)
bob*_*nce 36
使用DOM很容易找到DOM中的元素getElementsByTagName.事实上,你不想接近正则表达式.
如果您正在谈论的DOM是PHP DOMDocument,您可以执行以下操作:
$embeds= $document->getElementsByTagName('embed');
foreach ($embeds as $embed) {
$src= $embed->getAttribute('src');
$width= $embed->getAttribute('width');
$height= $embed->getAttribute('height');
$link= $document->createElement('a');
$link->setAttribute('class', 'player');
$link->setAttribute('href', $src);
$link->setAttribute('style', "display: block; width: {$width}px; height: {$height}px;");
$embed->parentNode->replaceChild($link, $embed);
}
Run Code Online (Sandbox Code Playgroud)
编辑重新编辑:
$dom->replaceChild($e, $a); // this line doesn't work
Run Code Online (Sandbox Code Playgroud)
是的,replaceChild将新元素替换为第一个参数,将要替换的子元素替换为第二个参数.这不是您可能期望的方式,但它与所有其他DOM方法一致.此外,它还是要替换子节点的父节点的方法.
(我class没有使用id,因为你不能在同一页面上调用多个元素id="player".)
| 归档时间: |
|
| 查看次数: |
22516 次 |
| 最近记录: |