我有一个 DOMDocument 对象,我想操作文本节点并将它们作为 HTML 字符串返回给对象。例如:
$dom=new DomDocument();
$dom->loadHTML('<html><body>This is [b]BBC[/b]</body></html>');
// $node is a text node
$html=parseBBC($node->nodeValue);
$frag=$dom->createDocumentFragment();
$frag->appendXML($html);
$node->parentNode->replaceChild($frag,$node);
echo $dom->saveHTML();
预期输出:
<html><body>This is <b>BBC</b></body></html>
实际输出:
empty string
编辑:
$dom=new DomDocument();
$dom->loadHTML('<html><body>This is[br]BBC</body></html>');
$xpath=new DOMXPath($dom);
$r=$xpath->query('//text()');
foreach($r as $el){
$str=trim(str_replace('[br]',"\n",$el->nodeValue));
$str='<p>'.preg_replace('/(\n|\r)+/','</p><p>',$str).'</p>';
$frag=$dom->createDocumentFragment();
$frag->appendXML($str);
$el->parentNode->replaceChild($frag,$el);
}
echo $dom->saveHTML();