Web Programming: Extracting The First Image from String

Have you ever wondered how to extract the first image listed in your second page content to your homepage while in the same time, usually you striptags your real content in second page to be displayed in your homepage.

hehehe,.. hopefully you don’t find yourself lost in the jumbled words arranged in the sentence above.

Here’s how you do it:

function get_first_image($param) {
$output = preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, $param, $matches);
if($matches) {
$first_img = $matches[1][0];
if(empty($first_img)){ //Defines a default image
$first_img = “”;
return $first_img;

Thanks to Radhite from apakabardunia.com and duniakherat.com for the insights!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s