0

I have a "get first image script" I am using that is all over the internet but am getting the error:

PHP Notice: Undefined offset: 0

the script is:

function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',$post->post_content, $matches);
$first_img = $matches [1] [0];
return $first_img;
}

can this be fixed?

  • 3
    Possible duplicate of [Notice: Undefined offset: 0 in](https://stackoverflow.com/questions/6549561/notice-undefined-offset-0-in) – Alex W Aug 07 '18 at 19:18
  • 1
    Use `print_r($matches);` to see what matches are available. Use `isset()` or `empty()` to first check it's available. – Rasclatt Aug 07 '18 at 19:20

3 Answers3

1

Based on your regex this could happen if the <img> tag has no src attribute or if there are no <img> tags at all.

As others have suggested you could fix this by checking $matches first, but I'd like to suggest an alternate approach that may be more robust for parsing html in php, since using regex to do this is discouraged.

function get_first_image() {
    global $post;
    $first_img = '';
    $dom = new DOMDocument();
    $dom->loadHtml($post->post_content);
    foreach ($dom->getElementsByTagName('img') as $img) {
        if ($img->hasAttribute('src')) {
            $first_image = $img->getAttribute('src');
            break;
        }
    }
    return $first_img;
}

The above function uses php's DOMDocument Class to iterate over <img> tags and get the src attribute if it exists. (Note: I removed the ob_start() and ob_end_clean() functions from your code because I don't understand what purpose they were serving)

0

Before operator:

$first_img = $matches [1] [0];

insert the line:

var_dump($matches);

Make sure, that $matches is an array, and has two dimensions.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
SergeF
  • 59
  • 4
0

You can do this:

$first_img = isset($matches[1][0]) ? $matches[1][0] : false;

Which will, then, return false if the first position in this two dimension array would not exist.

Rafael
  • 1,495
  • 1
  • 14
  • 25