使用PHP从HTML片段中解析值

时间:2013-10-16 20:28:52

标签: php html dom

我有以下html:

<span class="orig_line">
<a class="original" href="http://nucleify.org/">Nucleify <i class="externalLink icon-circle-arrow-right"></i></a>
&middot;

by <span class="author">Random Person</span>
&middot;
October 1, 2013
</span>

我正在使用sourceforge上提供的Simple HTML DOM解析器类,这是我正在使用的示例代码:

$newoutput = str_get_html($htmlCode);
$html  = new simple_html_dom();
$html->load($newoutput);
foreach($html->find('div#titlebar') as $date){
$n['date'] = $date->find('span.orig_line',0)->plaintext);
print $n['date'];
}

因为我只想要来自span(.orig_line)的October 1, 2013日期文本去除其中的任何进一步的html标签,而只是文本,我无法找到解决方法......

PS:我只想坚持SimpleHTMLDom类,没有phpQuery或DOMParsers。

谢谢。

1 个答案:

答案 0 :(得分:2)

由于“simple_html_dom”基于regexp,你可以使用regexp来匹配明文中的日期,如下所示:

require 'simple_html_dom.php';

$htmlCode = '
<div id="titlebar">
<span class="orig_line">
<a class="original" href="http://nucleify.org/">Nucleify <i class="externalLink icon-circle-arrow-right"></i></a>
&middot;

by <span class="author">Random Person</span>
&middot;
October 1, 2013
</span>
</div>';

$html  = new simple_html_dom();
$html->load($htmlCode);

foreach ($html->find('div#titlebar') as $date)
{
  $n = [];
  $plaintext = $date->find('span.orig_line', 0)->plaintext;
  preg_match('#[A-Z][a-z]+ \d{1,2}, \d{4}#is', $plaintext, $matches);
  $n['date'] = $matches[0];
  var_dump($n); # array (size=1) 'date' => string 'October 1, 2013' (length=15)
}