Php 如何使用标记包装所有文本节点?
如何使用标记包装所有文本节点 输入:Php 如何使用标记包装所有文本节点?,php,domdocument,Php,Domdocument,如何使用标记包装所有文本节点 输入: <p>Before <span>text1 <i>text2</i> text3</span> after</p> 文本前1文本后2文本后3 理想产出: <p><b>Before </b><span><b>text1 </b><i><b>text2</b></i>&
<p>Before <span>text1 <i>text2</i> text3</span> after</p>
文本前1文本后2文本后3
理想产出:
<p><b>Before </b><span><b>text1 </b><i><b>text2</b></i><b> text3</b></span><b> after</b></p>
文本前1文本后2文本后3
我的代码:
<?php
$html = <<<'HTML'
<div>
<p>Before <span>text1 <i>text2</i> text3</span> after</p>
</div>
HTML;
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$html = mb_convert_encoding( $html, "HTML-ENTITIES", "UTF-8" );
@$dom->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new DOMXPath( $dom );
$childrens = $xpath->query('//p[1]/descendant-or-self::node()');
foreach ( $childrens as $child ) {
$child->ownerDocument->saveHTML( $child );
}
echo $dom->saveHTML();
//text()
应该是xPath查询。//text()
应该是xPath查询。