如何用 DOMDocument 替换文本

How replace text with DOMDocument

需要将字母“a”更改为“1”,将“e”更改为“2”

这大约是html,实际上是更嵌套的

<body>
  <p>
    <span>sppan</span>
    <a href="#">link</a>
    some text
  </p>
  <p>
    another text
  </p>
</body>

预期输出

<body>
  <p>
    <span>spp1n</span>
    <a href="#">link</a>
    some t2xt
  </p>
  <p>
    anoth2r t2xt
  </p>
</body>

我认为您的预期输出有误(考虑到您的条件),但一般来说,可以使用 xpath 完成:

$html= '
[your html above]
';

$HTMLDoc = new DOMDocument();
$HTMLDoc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new DOMXPath($HTMLDoc);

# locate all the text elements in the html;:
$targets = $xpath->query('//*//text()');

#get the text from each element
foreach ($targets as $target) {
    $current = $target->nodeValue;

    #make the required changes
    $new = str_replace(["a", "e"],["1","2"], $current);
   
    #replace the old with the new
    $target->nodeValue=$new;
};
echo $HTMLDoc->saveHTML();

输出:

<body>
  <p>
    <span>spp1n</span>
    <a href="#">link</a>
    som2 t2xt
  </p>
  <p>
    1noth2r t2xt
  </p>
</body>