使用 PHP 从 HTML 代码段解析值


Parse value from HTML snippet using PHP

我有以下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上可用的简单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'];
}

由于我只想从跨度 (.orig_line) 中去除October 1, 2013日期文本,并且只删除文本,因此我找不到解决方法......

PS:我只想坚持使用SimpleHTMLDom类,而不是phpQuery或DOMParser。

谢谢。

由于"simple_html_dom"在很大程度上是基于正则表达式的,因此您可以使用正则表达式来匹配明文中的日期,如下所示:

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)
}