Home >Backend Development >PHP Tutorial >Typecho 截取文章第一张图片报错 Notice: Undefined offset: 0

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

WBOY
WBOYOriginal
2016-06-06 20:42:091224browse

函数代码

<code>function img_postthumb($content) {   
   preg_match_all("/\<img . alt="Typecho 截取文章第一张图片报错 Notice: Undefined offset: 0" >]*>/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";
   };   
}
</img.></code>

调用代码

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

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

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

回复内容:

函数代码

<code>function img_postthumb($content) {   
   preg_match_all("/\<img . alt="Typecho 截取文章第一张图片报错 Notice: Undefined offset: 0" >]*>/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";
   };   
}
</img.></code>

调用代码

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

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

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

改成这样试试?

<code>function thumbnail($content) {
    $pattern = '/\<img . alt="Typecho 截取文章第一张图片报错 Notice: Undefined offset: 0" >]*>/i';

    if (preg_match_all($pattern, $content, $thumbUrl)) {
        $imgSrc = $thumbUrl[1][0];
        echo $imgSrc;
    } else {
        echo 'noimage.jpg';
    }
}
</img.></code>

谢谢,已经可以了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn