Welcome Guest, Not a member yet? Register   Sign In
How to get first image from blog posts

(This post was last modified: 07-02-2015, 03:49 PM by chocovo.)


I am trying to get the first image of the text field "blog_post_content" and copy it to the field "blog_post_image".

I was looking on the Internet and tried something but I have an error.

In the controller I have this function:
PHP Code:
public function getfirstimage() {
$sql "SELECT blog_post_id, blog_post_content FROM tbl_blog_post";

$query $this->db->query($sql);
        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $row) {
$id $row->blog_post_id;
$texthtml $row->blog_post_content;
$first_img '';
$output preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i'$texthtml$matches);
$first_img $matches[1][0];
$data = array('blog_post_image' => $first_img);

The error is:
PHP Code:
MessageUndefined offset... in line "$first_img = $matches[1][0];" 

Can somebody help me with it?
Thank you.

there isn't any image in some of your records

If you're only trying to get the FIRST image, why use preg_match_all() which will get ALL images? Try using just preg_match() and then testing if $matches[1] exists before trying to use it. Additionally preg_match() will be slightly faster since it will stop trying to match after it finds the first entry if one exists:

$first_img = isset($matches[1]) ? $matches[1] : ''; //$first_img will be image, or empty string if it didn't exist.

Theme © iAndrew 2016 - Forum software by © MyBB