当前位置: 移动技术网 > IT编程>开发语言>PHP > php实现获取文章内容第一张图片的方法

php实现获取文章内容第一张图片的方法

2018年07月13日  | 移动技术网IT编程  | 我要评论

本文实例讲述了php实现获取文章内容第一张图片的方法。分享给大家供大家参考。具体分析如下:

采用php获取文章内容的第一张图片方法非常的简单,我们最常用的是使用正则了,感兴趣的朋友可以参考一下下面这段代码。

以下是关于选取文章中第一张图片的代码:

复制代码 代码如下:
$obj=m("news");
$info=$obj->where('id=1')->find();
//方法1*********
$socontent = $info['content'];
$soimages = '~<img [^>]* />~';
preg_match_all( $soimages, $socontent, $thepics );
$allpics = count($thepics[0]);
preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$thepics[0][0],$match);
dump($thepics);
if( $allpics> 0 ){
    echo "<img src='".$match[1]."' title='".$match[1]."'>";//获取的图片名称
}
else {
    echo "没有图片";
}
//**************
$socontent = $info['content'];
$soimages = '~<img [^>]* />~';
preg_match_all( $soimages, $socontent, $thepics );
$allpics = count($thepics[0]);
dump($thepics);
if( $allpics> 0 ){
    echo $thepics[0][0]; //获取的整个img属性
} else {
    echo "没有图片";
}
//**************
$soimages = '~<img [^>]* />~';
$str=$info['content'];
preg_match_all($soimages,$str,$ereg);//正则表达式把图片的整个都获取出来了
$img=$ereg[0][0];//图片
$p="#src=('|\")(.*)('|\")#isu";//正则表达式
preg_match_all ($p, $img, $img1);
   $img_path =$img1[2][0];//获取第一张图片路径
if(!$img_path){
    $img_path="images/nopic.jpg";
} //如果新闻中不存在图片,用默认的nopic.jpg替换 */
echo $img_path;
//*************88
$str=$info['content'];
preg_match_all("/<img.*\>/isu",$str,$ereg);//正则表达式把图片的整个都获取出来了
$img=$ereg[0][0];//图片
$p="#src=('|\")(.*)('|\")#isu";//正则表达式
preg_match_all ($p, $img, $img1);
   $img_path =$img1[2][0];//获取第一张图片路径
if(!$img_path){
    $img_path="images/nopic.jpg";
} //如果新闻中不存在图片,用默认的nopic.jpg替换 */
echo $img_path;

希望本文所述对大家的php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网