如果我对您的理解正确,那么这些方面的内容应该让您至少更接近您想去的地方:
$xpath = new DOMXPath($dom);
$targets = $xpath->query('//h2[last()]/following-sibling::p[not(position()=last())]');
foreach($targets as $target){
$target->parentNode->removeChild($target);}
$destination = $xpath->query('//p[last()]');
$template = $dom->createDocumentFragment();
$template->appendXML('<p>I am new here</p>');
$destination[0]->parentNode->insertBefore($template, $destination[0]);
echo $dom->saveHTML();
【讨论】:
-
太棒了!我所做的唯一更改是将代码行
$destination = $xpath->query('//p[last()]');更改为$destination = $xpath->query('//h2[last()]/following-sibling::p[last()]');。原始代码行保存了另一个位置,而不是最后一段,我想可能是因为目标内容中有两个div部分,我错过了提及(对不起!)。非常感谢! -
@lurie - 很高兴它对你有用!