2013-04-01 48 views
0

我想知道如何從mysql Query中提取第一個圖像的URL。從mysql查詢中提取第一個圖像標記

對於一個例子:

<p>Nowadays forums have become very popular, almost every site on the 
web have a forum. An Internet forum, bulletin board or message board, is 
an online discussion site where people can hold conversations in the 
form of posted messages.</p> 
<p>This is a list of top 10 free and open source software for creating your own forum.</p> 
<h3>1. phpBB</h3> 
phpBB is a free flat-forum bulletin board software solution that can 
be used to stay in touch with a group of people or can power your entire 
website.<br><br><img alt="" src="http://www.yoursite.com/phpbb.jpg" align="none"><br><br><h3>2. Simple Machines Forum</h3> 
SMF is a free, professional grade software package that allows you to set up your own online community within minutes.<br><br><img alt="" src="http://www.yoursite.com/smf.jpg" align="none"><br> 

從這個我需要提取http://www.yoursite.com/phpbb.jpg

我怎樣才能做到這一點。預先感謝

+0

我將獲取數據並在PHP –

+0

解析RTLM:http://php.net/dom –

+0

我覺得你應該去先學習教程,並學習一點MYsql,PHP和Mysql(至少) – jcho360

回答

3
$text = ' 
<p>Nowadays forums have become very popular, almost every site on the 
web have a forum. An Internet forum, bulletin board or message board, is 
an online discussion site where people can hold conversations in the 
form of posted messages.</p> 
<p>This is a list of top 10 free and open source software for creating your own forum.</p> 
<h3>1. phpBB</h3> 
phpBB is a free flat-forum bulletin board software solution that can 
be used to stay in touch with a group of people or can power your entire 
website.<br><br><img alt="" src="http://www.yoursite.com/phpbb.jpg" align="none"><br><br><h3>2. Simple Machines Forum</h3> 
SMF is a free, professional grade software package that allows you to set up your own online community within minutes.<br><br><img alt="" src="http://www.yoursite.com/smf.jpg" align="none"><br> 
'; 

$doc = new DOMDocument(); 
$doc->loadHTML($text); 
$xpath = new DOMXPath($doc); 
$images = $xpath->query("//img"); 
$first_image = $images->item(0); 
$firstsrc = $first_image->attributes->getNamedItem('src')->nodeValue; 
echo $firstsrc; 

OUTPUT:

http://www.yoursite.com/phpbb.jpg 

更新:另一個簡短的答案通過@uınbɐɥs:

$doc = DOMDocument::loadHTML($text); 
$firstsrc = $doc->getElementsByTagName('img')->item(0)->getAttribute('src'); 
echo $firstsrc; 
+2

[總是有一個更短的路](http://codepad.org/26vg7uJz) –

0

您可以使用簡單的HTML DOM解析器庫。 其簡單和易於

$html = str_get_html('Your HTML string here'); 

// Find all images 
$image = $html->find('img',0); 

這會給你的第一個圖像標籤

相關問題