在两个选择器块之间查找文本


Finding text between two blocks of selector

那么,这就是我的代码:

<div id="first">
 <div id="third">Lorem</div>
   Lorem Ipsum Dolorez [...]
 <script></script>
  ....
 <div id="second">
  Lorem Ipsum[...]
  <a href=""/>
 </div>
  ....
</div>

我需要得到Lorem Ipsum Dolorez [...],它在两个div块之间一个div块和一个script块,以及Lorem Ipsum[...],它在div内,但没有超链接。

我试着用simple_html_dom.php,但我不知道怎么做。

编辑:这是一个网站-我不能更改这个代码。

您可以使用DOM库和xpath(注释中嵌入的解释)选择这些节点:

$html = '
    <div id="first">
 <div id="third">Lorem</div>
    Lorem Ipsum Dolorez [...]
     <script></script>
    this never gets picked up
   <div id="second">
     Lorem Ipsum[...]
       <a href=""></a>
        <span> this span is extraced since its not an anchor element </span>
    </div>
  </div>';
$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$first_lorem = $xpath->query('//div[@id="first"]/div[@id="third"]/following-sibling::text()[following::script]');
// first, find the div#first and inside that a div#third ...
// ... and take text node siblings of that div ...
// ... if those siblings have a script node following them (so if there's a <script> after them)
$first_lorem_html = '';
// loop the results and concat the html output
foreach ($first_lorem as $node) {
    $first_lorem_html .= $doc->saveHTML($node);
}
print $first_lorem_html;
// get the every child of div#second except the ones named 'a'
$second_lorem = $xpath->query('//div[@id="second"]/node()[name() != "a"]');
$second_lorem_html = '';
foreach ($second_lorem as $node) {
    $second_lorem_html .= $doc->saveHTML($node);
}
print $second_lorem_html;

尝试使用strip_tags php函数。例子:

echo strip_tags('<div id="second">Lorem Ipsum[...]<a href=""/></div>');

的回报:

Lorem Ipsum[…]

http://php.net/manual/en/function.strip-tags.php

根据simple_html_dom引用:http://simplehtmldom.sourceforge.net/

你可以这样做:

   $html->find('div[id=third]', 0)->plaintext