时间:2021-07-01 10:21:17 帮助过:14人阅读
- <code>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";
- };
- }
- </img.*?src\=\"(.*?)\"[^></code>
调用代码
- <code><!--?php echo img_postthumb($this--->content); ?>
- </code>
有图片的文章截取后没有错误,没有图片的文章会报错:Notice: Undefined offset: 0
请问如何改进才没有报错。
函数代码
- <code>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";
- };
- }
- </img.*?src\=\"(.*?)\"[^></code>
调用代码
- <code><!--?php echo img_postthumb($this--->content); ?>
- </code>
有图片的文章截取后没有错误,没有图片的文章会报错:Notice: Undefined offset: 0
请问如何改进才没有报错。
改成这样试试?
- <code>function thumbnail($content) {
- $pattern = '/\<img.*?src\=\"(.*?)\"[^>]*>/i';
- if (preg_match_all($pattern, $content, $thumbUrl)) {
- $imgSrc = $thumbUrl[1][0];
- echo $imgSrc;
- } else {
- echo 'noimage.jpg';
- }
- }
- </img.*?src\=\"(.*?)\"[^></code>
谢谢,已经可以了。