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 のみを返しますが、要素間のノード<br/>は TextNodes です。

nextSiblingTextNode も選択するには、DOMNodeの -property を使用します。

例 (ネイティブ 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 に答える