我正试图用PHP刮信息,有他们的数据像这样:
<br>1998 - <a href="http://example.com/movie/id/2345">A Night at the Roxburry<a/>
我需要得到<br>
和<a>
标签之间的年份。我已经通过使用PHP简单DOM HTML解析器获得了电影的标题。这是我用来解析标题
foreach($dom->getElementsByTagName('a') as $link){
$title = $link->getAttribute('href');
}
我试着使用:
$string = '<br>1998 - <a href="http://example.com/movie/id/2345">A Night at the Roxburry<a/>';
$year = preg_match_all('/<br>(.*)<a>', $string);
但是它没有找到在<br>
和<a>
标签之间的年份。有人知道我怎么才能找到年份吗?
试试这个:
<?php
$subject = '<br>1998 - <a href="http://site.com/movie/id/2345">A Night at the Roxburry<a/>';
$pattern = '/<br>[0-9]{4}/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
注意,如果year以其他格式显示,您可以更改模式。如果你想看到两个标签之间的所有内容,你可以使用$pattern = '/<br>.*<a/';
或任何其他适合你的。
您使用的表达式:$year = preg_match_all('/<br>(.*)<a>', $string);
将在<br>
和<a>
之间找到文本,但在您的示例中,您在任何地方都没有<a>
。试着寻找<br>
和<a
之间的文本,像这样:
$year = preg_match_all ('/<br>([^<]*)<a/', $string);
注意,我还将.
更改为[^<]
,以确保它将在下一个标签处停止,否则它将匹配这样的字符串:
<br>foo<br><br>1998 - <a href="http://site.com/movie/id/2345">A Night at the Roxburry<a
因为它们以<br>
开头,以<a
结尾,但这可能不是你需要的,任何你的年份都将是这样的:
foo<br><br>1998 - <a href="http://site.com/movie/id/2345">A Night at the Roxburry