1 回答

TA貢獻1784條經驗 獲得超2個贊
您需要做的是將文檔加載到 中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 關注
- 87 瀏覽
添加回答
舉報