php - 获取没有类或标签的文本html dom解析器

问题描述 投票:0回答:1

我已经陷入了一个典型的案例..我需要一些表中没有类或任何标签的文本..这只是一个纯文本..我只想得到这个文本。我需要抓我想要这篇文章。我该怎么做

我的HTML

<td class="example">
  <strong>text in strong</strong><br>
  <strong>2nd text in strong:</strong> 

       I WANT THIS TEXT
  <br> 

  <strong><span style="color:red;">another text</span></strong>
  <br> 
  <a href="#" target="_blank">Click Here</a>
</td>

到目前为止我已经尝试了:因为我们必须刮掉多行,所以我使用的是foreach循环

 foreach($html->find('td.example') as $element){

        echo $element->find('strong', 1)->outertext . "<br/>";

}
php web-scraping domparser
1个回答
0
投票

如果我们假设您的html字符串在变量$ html中,则以下正则表达式应该起作用:

/** Replace the carriage return with '^' */
$html = str_replace("\r", "^", $html);
/** Replace the line feed with '~' */
$html = str_replace("\n", "~", $html);

/** regular expression is used to match the text */
preg_match("/<strong>.*<\/strong><br>.*<strong>.*<\/strong>(.+)<br><strong><span style="color:red;">.*<\/span><\/strong>/iU", $html, $matches);

/** The '^' is replaced with '\r' */
$matches[1]  = str_replace("^", '\r', $matches[1]);

/** The '~' is replaced with '\n' */
$text        = str_replace("~", '\n', $matches[1]);

变量$ text包含匹配文本

© www.soinside.com 2019 - 2024. All rights reserved.