使用dom将锚文本移动到锚标记之外


Move anchor text outside of anchor tag using dom

我使用PHP的DOMDocument来解析HTML文档的各个部分。

问题:

所有锚点(不是指向锚点的链接)都是这样设置的:

<a name="_Toc1234567">Overview of Data</a>

我希望格式是这样的:

<a name="_Toc1234567"></a>Overview of Data

文档中有很多这样的内容,但在所有情况下,锚都有一个指定的名称——始终是唯一的。没有为所有链接指定名称。

到目前为止,我有这个:

<?php
$d = new DOMDocument;
$d->loadHTML(file_get_contents('source.html'));
$anchors = $d->getElementsByTagName('a');
foreach ($anchors as $anchor) {
      $name = $anchor->getAttribute('name'); 
      $atext = $anchor->nodeValue;
      if (isset($name)) {
        // move the anchor text outside of the anchor tag
        // like this  <a name="_Toc1234567"></a>Anchor text
      }
}
$final = $d->saveHTML();
file_put_contents("result.html", $final);
?>

如果jQuery对您来说还可以,您可以使用以下代码:

$.each($('a'), function(){
    var content = $(this).html();
    $(this).html('');
    $(this).after(content);
});

Fiddle:http://jsfiddle.net/nikoloza/xt9ja4e0/

您可以创建一个新的文本节点

 $textNode = $d->createTextNode ( $anchor->nodeValue );

然后清空nodeValue

 $anchor->nodeValue = '';

但据我所知,您需要父节点和下一个兄弟节点来添加$textNode。

阅读以下内容和评论以获得想法:http://php.net/manual/de/domnode.insertbefore.php