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

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

WBOY
Release: 2016-06-06 20:42:09
Original
1223 people have browsed it

函数代码

<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>
Copy after login
Copy after login

调用代码

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

有图片的文章截取后没有错误,没有图片的文章会报错: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>
Copy after login
Copy after login

调用代码

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

有图片的文章截取后没有错误,没有图片的文章会报错: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>
Copy after login

谢谢,已经可以了。

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template