zblogphp怎么取出文章内容中的图片用在首页栏目页

admin2020-07-081115

首页要知道要想取出文章中的图片,必须用正则表达式去提取。

我的需求:在首页显示文章中的3个图片。

实际情况:3个图片在文章中,且文章中的图片不止3个。

思路:先用取出文章内容->提取出所有图片->留下前三张图片->通过遍历进行显示。

image.png

完整代码如下:

//先取出图片数据
{php}
    $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
    //获取文章信息
    $article = GetPost(28);
    //获取文章内容
    $content = $article->Content;
    //从文章中提取图片
    preg_match_all($pattern,$content,$matchContent);
    //文章中有很多图片时,可以通过array_slice()来提取其中想要的一部分
    $imgs = array_slice($matchContent[1],0,3);
{/php}    
//进行显示              
{foreach $imgs as $img }
    <a class="listimg" href="{$article.Url}">
	<div class="small-img"><img src="{$img}" alt=""></div>
    </a>
{/foreach}


网友评论