请告诉我如何遍历段落中的所有文本节点?毕竟,它们可以达到2-3级。
例如,请采用以下段落:
<p>Lorem <i>ipsum dolor</i> sit <span>amet, <b><i>consectetur</i> adipisicing</b> elit</span>. Odit, sunt?</p>
您要在其中处理所有文本节点并将其返回到其位置。
$content = '<p>Lorem <i>ipsum dolor</i> sit <span>amet, <b><i>consectetur</i> adipisicing</b> elit</span>. Odit, sunt?</p>';
$html = new DOMDocument();
$html->loadHTML($content);
$xpath = new DOMXpath($html);
$elements = $xpath->query('//descendant-or-self::p//node()');
// My processor (not working...)
foreach ($elements as $element) {
// Processed, only text nodes (not working...)
if ( $element->nodeType == 3 ) {
function() {
return $element->nodeValue = '<span style="background-color: yellow;">' . $element->nodeValue . '</span>';
}
}
// return to the place
echo $element->C14N();
}
你需要得到这样的结果:
<p>
<span style="background-color: yellow;">Lorem </span>
<i>
<span style="background-color: yellow;">ipsum dolor</span>
</i>
<span style="background-color: yellow;">sit </span>
<span>
<span style="background-color: yellow;">amet, </span>
<b><i>
<span style="background-color: yellow;">consectetur</span>
</i>
<span style="background-color: yellow;">adipisicing</span>
</b>
<span style="background-color: yellow;">elit</span>
</span>
<span style="background-color: yellow;">. Odit, sunt?</span>
</p>