发布于 2014-11-22 12:55:05 | 206 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的PHP教程,程序狗速度看过来!

PHP开源脚本语言

PHP(外文名: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,入门门槛较低,易于学习,使用广泛,主要适用于Web开发领域。PHP的文件后缀名为php。


本文为大家讲解的是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;

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务