博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP获取网站中各文章的第一张图片的代码示例
阅读量:7182 次
发布时间:2019-06-29

本文共 986 字,大约阅读时间需要 3 分钟。

调取文章中的第一张图作为列表页缩略图是很流行的做法,WordPress中一般主题默认也是如此,那我们接下来就一起来看看PHP获取网站中各文章的第一张图片的代码示例
1
2
3
4
5
6
7
8
9
10
11
12
<?php
$temp
=mt_rand(1,4);
$pattern
=
"/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"
;
$content
=
$article
->Content;
//文章内容
preg_match_all(
$pattern
,
$content
,
$matchContent
);
if
(isset(
$matchContent
[1][0])){
  
$temp
=
$matchContent
[1][0];
}
else
{
  
$temp
=
"images/random/$temp.jpg"
;
//需要在相应位置放置4张jpg的文件,名称为1,2,3,4
}
  
?>

以上代码默认调用文章首张图片,当文章没有图片的时候,随机调用主题style/images/random/下的1.jpg、2.jpg、3.jpg、4.jpg图片。如果不想调用随机图片,可以修改一下:

1
2
3
4
5
6
7
8
9
10
11
<?php
$pattern
=
"/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/"
;
$content
=
$article
->Content;
//文章内容
preg_match_all(
$pattern
,
$content
,
$matchContent
);
if
(isset(
$matchContent
[1][0])){
  
$temp
=
$matchContent
[1][0];
}
else
{
  
$temp
=
"./images/no-image.jpg"
;
//在相应位置放置一张命名为no-image的jpg图片
}
  
?>

调用文章首张图片,如果文章没有图片就调用默认图片no-image.jpg

https://www.jb51.net/article/84729.htm

转载地址:http://shukm.baihongyu.com/

你可能感兴趣的文章
我的友情链接
查看>>
RIP、端口DHCP
查看>>
MySQL Explain命令详解--表的读取顺序,数据读取操作的类型等
查看>>
Windows 10剪贴板历史记录清理
查看>>
使用zabbix的ICMP Ping模版实现对客户端网络状态的监控
查看>>
90后美女的全能测试蜕变之路
查看>>
单网卡安装pptpd
查看>>
Cisco路由器配置ADSL上网
查看>>
qemu-kvm 启动
查看>>
IPSec ×××配置总结 2
查看>>
ImportFileHandler 附件上传
查看>>
curl提示不支持https协议解决方法
查看>>
Spring定时任务@Scheduled的cron表达式
查看>>
centos 防火墙设置
查看>>
SSH Secure Shell Client
查看>>
Linksys e3200初试tomato系统
查看>>
Runtime 类的使用
查看>>
Cassandra删除数据的坑
查看>>
AGC018D Tree and Hamilton Path(树+树的重心)
查看>>
【Codeforces #168 Div1 & Div2】Solutions
查看>>