PHP注意:未定义的偏移量:0可修复?
我有一个“get first image script”(获取第一个图像脚本),我正在使用该脚本,该脚本在互联网上随处可见,但我发现了错误: 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=[\'"]([^\'"]+)[\'"].*&
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;
}