PHP: แสดง thumbnail ของภาพแรกใน Post

นำภาพแรกใน post (ในที่นี้สมมุติข้อความใน post ไว้ใน $post ในบรรทัดที่ 10) มาแสดง (บรรทัดที่ 22)
[code lang=”php”]
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8">
<title>ทดสอบ Create thumbnail</title>
</head>
<body>
<?php
function catch_that_image() {
$post = ‘some text with two pictures: <img src="http://www.example.com/image1.jpg" /> <img src="http://www.example.com/image2.png" />’;
$first_img = ”;
$output = preg_match_all(‘/<img.+src=[\’"]([^\’"]+)[\’"].*>/i’, $post, $matches);
$first_img = $matches[1][0];
/*$second_img = $matches[1][1];*/

if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
?>
<p><img src="<?php echo catch_that_image() ?>" width="110"></p>
</body>
</html>
[/code]

ดัดแปลงโค๊ดมาจาก http://www.wprecipes.com, http://css-tricks.com