0

我有一个<p>标签,其中包含由标签分隔的文本,<br>如下所示:

<p>
    <small>Some text here</small>
    This is the text that want to remove
    <br> another text here
    <br> more text here
    <br> also there are other tags like <em>this one</em>
</p>

我要选择的元素在第一个<br>标签之后直到最后,我目前正在使用QueryPath库,我只获取 html 标签和它们之间的文本,而没有获取其他未被标签包围的文本.

例如,我只得到<br>标签和<em></em>带有此代码的标签:

$qp->find('div > p')->children('br')->eq(0)->nextAll();

所以我尝试获取整个<p>标签并尝试从<small>标签中删除元素,直到第一个<br>标签:

// remove the text after the small tag
$qp->branch('div > p')->children('small')->textAfter(''); // didn't work

// although when I return the textAfter I get the text
// so setting it to an empty string didn't work

// I can only remove the small tag
$qp->branch('div > p')->children('small')->remove();

QueryPath 库是Dom本机扩展之上的一个包装器,因此任何使用 Dom 扩展的解决方案都可以工作。

4

1 回答 1

1

用于选择节点(例如nextAll()children())的 QueryPath 方法仅返回 ElementNodes,但 -elements 之间的节点<br/>是 TextNodes。

使用nextSiblingDOMNode 的 -property 也可以选择 TextNodes。

示例(使用原生 DOM):

<?php
$dom = new DOMDocument();

$dom->loadXML('<p>
    <small>Some text here</small>
    This is the text that want to remove
    <br/> another text here
    <br/> more text here
    <br/> also there are other tags like <em>this one</em>
</p>');
$text='';
$node = $dom->getElementsByTagName('br')->item(0);
while($node->nextSibling){
  $node=$node->nextSibling;
  $text.=$node->textContent;
}
echo $text;
//output:
//another text here more text here also there are other tags like this one 
?>
于 2013-12-28T09:18:29.337 回答