0

我想知道如何从 mysql 查询中提取第一个图像 URL。

例如:

<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

我怎样才能做到这一点。预先感谢

4

2 回答 2

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;

输出:

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

更新:@uınbɐɥs 的另一个简短回答:

$doc = DOMDocument::loadHTML($text);
$firstsrc = $doc->getElementsByTagName('img')->item(0)->getAttribute('src');
echo $firstsrc;
于 2013-04-01T18:26:53.580 回答
0

您可以使用简单的 HTML dom 解析器库。它简单易行

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

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

这将为您提供第一个图像标签

于 2013-04-01T18:44:56.707 回答