Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP注意:未定义的偏移量:0可修复?_Php_Wordpress - Fatal编程技术网

PHP注意:未定义的偏移量:0可修复?

PHP注意:未定义的偏移量:0可修复?,php,wordpress,Php,Wordpress,我有一个“get first image script”(获取第一个图像脚本),我正在使用该脚本,该脚本在互联网上随处可见,但我发现了错误: PHP注意:未定义的偏移量:0 剧本是: function get_first_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*&

我有一个“get first image script”(获取第一个图像脚本),我正在使用该脚本,该脚本在互联网上随处可见,但我发现了错误:

PHP注意:未定义的偏移量:0

剧本是:

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;
}
函数get_first_image(){ 全球$员额,$员额; $first_img=''; ob_start(); ob_end_clean(); $output=preg_match_all('//i',$post->post_content,$matches); $first_img=$matches[1][0]; 返回$first\u img; } 这可以解决吗?

在操作员之前:

$first_img = $matches [1] [0];
插入以下行:

var_dump($matches);
确保$matches是一个数组,并且有两个维度。

您可以这样做:

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

如果二维数组中的第一个位置不存在,则返回false。

根据您的正则表达式,如果
注意:我删除了
ob\u start()
ob\u end\u clean(),则可能会发生这种情况
来自您的代码的函数,因为我不明白它们的用途)

可能重复使用
打印($matches)
查看可用的匹配项。使用
isset()
empty()
首先检查它是否可用。
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;
}