[英]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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.