我正在从数据库中获取几个段落,并尝试将这些段落分成一个包含正则表达式和不同类的数组。但没有任何效果。
我试图这样做:
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
可捕获的致命错误:无法将类 DOMElement 的对象转换为第 20 行 C:''Inetpub''vhosts''bestcamdirectory.com''httpdocs''sandbox''model''ReviewContentExtractor.php 中的字符串
为什么我会收到消息,有没有一种简单的方法可以从字符串中提取所有段落?
更新:
public function get_first_para(){
$pattern="/<p>(.+?)<'/p>/i";
preg_match_all($pattern,$this->review,$matches,PREG_PATTERN_ORDER);
return $matches;
}
我更喜欢第二种方式..但它也不能很好地工作..
DOMDocument::getElementsByTagName 返回一个可迭代但不是数组的 DOMNodeList 对象。在foreach
中,$paragraph
变量是 DOMElement 的一个前提,因此简单地将其用作字符串是行不通的(正如错误所解释的那样)。
你想要的是 DOMElement 的文本内容,它可以通过这些 textContent 属性(继承自 DOMNode 类)获得:
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 的错误处理部分。
编辑
既然你坚持使用正则表达式,你可以这样去做:
preg_match_all('!<p>(.+?)</p>!sim',$html,$matches,PREG_PATTERN_ORDER);
模式修饰符:m
表示多行,s
表示.
可以匹配行端,i
表示不区分大小写。