1

我尝试了在这个问题上发布的所有解决方案。尽管它与我的问题相似,但它的解决方案对我不起作用。

我正在尝试获取外部的纯文本,<b>它应该在<div id="maindiv>.

<div id=maindiv>
     <b>I don't want this text</b>
     I want this text
</div>

$part是包含<div id="maindiv">. 现在我尝试了这个:

$part->find('!b')->innertext;

上面的代码不起作用。当我尝试这个

$part->plaintext;

它返回了像这样的所有纯文本

I don't want this text I want this text

我阅读了官方文档,但没有找到任何解决此问题的方法:

4

2 回答 2

0

询问:

$selector->query('//div[@id="maindiv"]/text()[2]')

解释:

//               - selects nodes regardless of their position in tree

div              - selects elements which node name is 'div'

[@id="maindiv"]  - selects only those divs having the attribute id="maindiv"

/                - sets focus to the div element

text()           - selects only text elements

[2]              - selects the second text element (the first is whitespace)

                   Note! The actual position of the text element may depend on
                   your preserveWhitespace setting.

                   Manual: http://www.php.net/manual/de/class.domdocument.php#domdocument.props.preservewhitespace

例子:

$html = <<<EOF
<div id="maindiv">
     <b>I dont want this text</b>
     I want this text
</div>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXpath($doc);   

$node = $selector->query('//div[@id="maindiv"]/text()[2]')->item(0);
echo trim($node->nodeValue); // I want this text
于 2013-05-04T10:18:12.123 回答
0

删除第<b>一个:

$part->find('b', 0)->outertext = '';
echo $part->innertext; // I want this text
于 2014-03-16T20:07:09.500 回答