2013-03-17 29 views
1

我想用PHP有像這樣的數據報廢信息:如何在2個標籤之間找到廢料信息?

<br>1998 - <a href="http://site.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://site.com/movie/id/2345">A Night at the Roxburry<a/>'; 
$year = preg_match_all('/<br>(.*)<a>', $string); 

但它沒有找到當年那個在<br><a>標籤之間。有誰知道我能做些什麼來找到這一年?

回答

1

您正在使用的表達:$year = preg_match_all('/<br>(.*)<a>', $string);會發現<br><a>之間的文本,但在你的例子你沒有<a>任何地方。試着這樣<br><a之間尋找文本:

$year = preg_match_all ('/<br>([^<]*)<a/', $string); 

注,我也改變.[^<],以確保它會停在一個標籤,otherwith它將匹配這樣的字符串:

<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 
2

試試這個:

<?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); 
?> 

注意,如果今年在一些其他格式顯示,你可以改變模式。如果您想查看兩個標籤之間的所有內容,您可以使用$pattern = '/<br>.*<a/';或其他任何適合您的標籤。

相關問題