php获取内容中的所有图片列表并输出的方法,这个在需要提取一段内容中的图片或者需要提取一段内容中的第一张图片作为内容的缩略图的时候可以用的上,具体的实现代码如下,作者在自己的项目中使用目前还没有存在问题,如果你发现这段代码有什么问题,欢迎留言指正。
function getImgList($content,$order='ALL'){ $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/"; preg_match_all($pattern,$content,$match); if(isset($match[1])&&!empty($match[1])){ if($order==='ALL'){ return $match[1]; } if(is_numeric($order)&&isset($match[1][$order])){ return $match[1][$order]; } } return []; }
以上代码的用法如下:
(1)提取一段内容中的所有图片
print_r(getImgs($content));
如果存在图片的话,得到的结果将是如下样子:
Array
(
[0] => upfiles/php.hhsy.cc/01_4.jpg
[1] => upfiles/php.hhsy.cc/01_3.jpg
[2] => upfiles/php.hhsy.cc/01_1.jpg
)
(2)提取一段内容中的第一张图片
print_r(getImgs($content,0));
结果将如下:
upfiles/php.hhsy.cc/01_4.jpg