下面的代码打印出博客文章中的所有 IMG 标签,然后随机显示一张图片。如何制作代码以使其始终显示第一张图像?
$DOM = new DOMDocument();
$string =
'Test hei
<img src="bild1e1">
string
<img src="bilde2" />
Mere tekst her........
<img src="bilde3" />
<img src="bilde4" />
fffffff
';
preg_match_all('/<img[^>]+>/i', $string, $var);
echo 'Det finnes totalt <strong>' . count($var[0]) . '</strong> img-tager i stringen. Disse ble funnet:<br>';
foreach($var[0] as $id => $value)
echo '#' . ($id+1) . ': ' . htmlspecialchars($value) . '<br>';
echo '<br><br>';
$randomPic = array_rand($var[0], 1);
$DOM->loadHTML($var[0][$randomPic]);
$tag = $DOM->getElementsByTagName('img');
foreach ($tag as $i)
echo '<strong>Random bilde-URL:</strong> ' . $i->getAttribute('src');