首页 > 开发 > php > 正文

Typecho 截取文章第一张图片报错 Notice: Undefined offset: 0

2017-09-06 15:00:21  来源:网友分享

函数代码

function img_postthumb($content) {      preg_match_all("/\<img.*?src\=\"(.*?)\"[^>]*>/i", $content, $thumbUrl);   $img_src = $thumbUrl[1][0];   $img_counter = count($thumbUrl[0]);     switch ($img_counter > 0) {          case $img_counter = 1:              echo $img_src;            break;          default:              echo "noimage.jpg";   };   }

调用代码

<?php echo img_postthumb($this->content); ?>  

有图片的文章截取后没有错误,没有图片的文章会报错:Notice: Undefined offset: 0

请问如何改进才没有报错。

解决方案

改成这样试试?

function thumbnail($content) {    $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i';    if (preg_match_all($pattern, $content, $thumbUrl)) {        $imgSrc = $thumbUrl[1][0];        echo $imgSrc;    } else {        echo 'noimage.jpg';    }}