Tuesday, May 24, 2011

Get the first image only from a content - PHP

//This is the function, Replace your content to $content variable

function catch_that_image() {
  $content = "Add your content that having image";
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('//i', $content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "noimage.jpg"; //Give the path of noimage.jpg
  }
  return $first_img;
}

//And get the output by calling the function

echo  catch_that_image();

This is very useful when we have to get the content from the database that will have image inside the same field and when we wanted to grab the image for a thumbnail or something

No comments:

Post a Comment