PHP获取文章内容第一张图片,并截取内容前200字符作为描述

1565

PHP获取文章内容第一张图片发布文章时


如果没有封面图则自动匹配文章内容第一张图片作为封面

$html_string =htmlspecialchars_decode($item['news_content']); //文章内容
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$html_string,$matchContent);
if(isset($matchContent[1][0])){
    $item['news_pic']=$matchContent[1][0];
}else{
    $item['news_pic']="/uploads/noimg.jpg";//在相应位置放置一张命名为no-image的jpg图片
}

PHP截取文章内容前100字作为文章描述

$html_string =htmlspecialchars_decode($item['news_content']); //文章内容
//将空格替换成空
$content = str_replace(" ","",$html_string);
//函数剥去字符串中的HTML、XML以及PHP的标签,获取纯文本内容
$contents = strip_tags($content);
//返回字符串中的前100字符串长度的字符
$item['desc'] =  mb_substr($contents, 0, 100, 'utf-8');