【问题标题】:Getting all the paragraphs in a string extract获取字符串提取中的所有段落
【发布时间】:2012-08-07 06:15:14
【问题描述】:

我正在从数据库中提取几段,并尝试将这些段落分成一个带有正则表达式和不同类的数组。但没有任何效果。

我尝试过这样做:

   public function get_first_para(){
        $doc = new DOMDocument();
    $doc->loadHTML($this->review);
    foreach($doc->getElementsByTagName('p') as $paragraph) {
      echo $paragraph."<br/><br/><br/>";
    } 
 }

但我明白了:

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Unexpected end tag : p in Entity, line: 9 in C:\Inetpub\vhosts\bestcamdirectory.com\httpdocs\sandbox\model\ReviewContentExtractor.php on line 18

可捕获的致命错误:第 20 行的 C:\Inetpub\vhosts\bestcamdirectory.com\httpdocs\sandbox\model\ReviewContentExtractor.php 中的 DOMElement 类的对象无法转换为字符串

为什么我会收到消息,有没有一种简单的方法可以从字符串中提取所有段落?

更新:

   public function get_first_para(){
         $pattern="/<p>(.+?)<\/p>/i";
         preg_match_all($pattern,$this->review,$matches,PREG_PATTERN_ORDER);
         return $matches;
     }

我更喜欢第二种方式..但它也不好用..

【问题讨论】:

标签: php


【解决方案1】:

DOMDocument::getElementsByTagName 返回一个可迭代但不是数组的 DOMNodeList 对象。在foreach 中,$paragraph 变量是DOMElement 的一个实例,因此仅将其用作字符串是行不通的(正如错误所解释的那样)。

你想要的是 DOMElement 的文本内容,可以通过那些(继承自 DOMNode 类)的textContent 属性获得:

foreach($doc->getElementsByTagName('p') as $paragraph) {
  echo $paragraph->textContent."<br/><br/><br/>"; // for text only
} 

或者如果您需要 DOMNode 的完整内容,您可以使用DOMDocument::saveHTML

foreach($doc->getElementsByTagName('p') as $paragraph) {
    echo $doc->saveHTML($paragraph)."<br/><br/><br/>\n"; // with the <p> tag

    // without the <p>
    // if you don't need the containing <p> tag, you can iterate trough it's childs and output them
    foreach ($paragraph->childNodes as $cnode) {
         echo $doc->saveHTML($cnode); 
    }
}

至于您的 loadHTML 错误,html 输入无效,您可以使用以下命令抑制警告:

libxml_use_internal_errors(true); // before loading the html content

如果您需要这些错误,请参阅手册的libxml's error handling part

编辑

既然你坚持使用正则表达式,那么你可以这样做:

preg_match_all('!<p>(.+?)</p>!sim',$html,$matches,PREG_PATTERN_ORDER);

pattern modifiersm 表示多行,s 表示 . 可以匹配行尾,i 表示不区分大小写。

【讨论】:

  • 那不好。它做了什么,它将所有内容转换为字符串并在此过程中抛出错误......我想我更喜欢正则表达式
  • 你仍然可以使用libxml_get_errors 得到错误,还可以查看html tidy 项目来美化随机的 html 输入,这可能证明自己很有用。
  • 查看我的更新。我需要保存 html 元素,所以 textContent 不好。刮得不好。我认为正则表达式会是一个更好的解决方案
  • 我添加了一个示例,它将导出 DOMNode 的 html 而不是它的文本内容,我认为这就是您想要的。用正则表达式解析 html 是 generally a bad idea.
  • @complex857 我在等那个链接:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
相关资源
最近更新 更多