我有一个包含由<br>标记分隔的文本的<p>标记,如下所示:
<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扩展的解决方案都可以工作。
发布于 2013-12-28 17:18:29
用于选择节点的查询路径方法(例如nextAll()或children())仅返回ElementNodes,但<br/>-elements之间的节点为TextNodes。
使用DOMNode的nextSibling-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
?>https://stackoverflow.com/questions/20812551
复制相似问题