1 回答
TA贡献1816条经验 获得超6个赞
您需要做的是将文档加载到 中DOMDocument,然后选择元素中的所有相关元素<div id="main">并替换其中的文本。
像这样的东西
$find = ['(', ')', '?', '!']; // characters to find
$replace = ['( ', ' )', ' ?', ' !']; // replacements
// create a "text-contains" selector for all the characters
$selector = implode(' or ', array_map(function($char) {
return sprintf('contains(text(), "%s")', $char);
}, $find));
// create an XPath query to get the text nodes
$query = sprintf('//div[@id="main"]//*[%s]/text()', $selector);
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXPath($doc);
$elements = $xpath->query($query);
foreach ($elements as $element) {
// You need to decode the entities when working directly with text nodes
$element->nodeValue = html_entity_decode(str_replace($find, $replace, $element->nodeValue));
}
$newContent = $doc->saveHTML();
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报