本文实例讲述了php实现获取文章内容第一张图片的方法。分享给大家供大家参考。具体分析如下:
采用php获取文章内容的第一张图片方法非常的简单,我们最常用的是使用正则了,感兴趣的朋友可以参考一下下面这段代码。
以下是关于选取文章中第一张图片的代码:
$obj=M("News");
$info=$obj->where('id=1')->find();
//方法1*********
$soContent = $info['content'];
$soImages = '~]* />~';
preg_match_all( $soImages, $soContent, $thePics );
$allPics = count($thePics[0]);
preg_match('//i',$thePics[0][0],$match);
dump($thePics);
if( $allPics> 0 ){
echo "";//获取的图片名称
}
else {
echo "没有图片";
}
/
echo $img_path;
/
echo $img_path;
php获取文章html内容第一张图片地址
php实现获取文章html内容第一张图片地址,示例采用正则表达式实现,代码仅供参考。也可以稍作修改即可获取文章内容中全部图片地址,具体业务具体扩展。
// 注意这个变量中img标签末尾的细节变化 $str=''; echo get_html_first_imgurl($str); exit; function get_html_first_imgurl($html){ $pattern = '~]*[s]?[/]?[s]?>~'; preg_match_all($pattern, $html, $matches);//正则表达式把图片的整个都获取出来了 $img_arr = $matches[0];//全部图片数组 $first_img_url = ""; if (!empty($img_arr)) { $first_img = $img_arr[0]; $p="#src=('|")(.*)('|")#isU";//正则表达式 preg_match_all ($p, $first_img, $img_val); if(isset($img_val[2][0])){ $first_img_url = $img_val[2][0]; //获取第一张图片地址 } } return $first_img_url; }
希望本文所述对大家的PHP程序设计有所帮助。



