PHP提取文章首图方案概述
本实例详解了使用PHP提取文章内首张图示的技术方案,供开发者参考借鉴。核心逻辑在于解析HTML结构并定位图像元素。
借助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 "没有图片";
}
//**************
$soContent = $info['content'];
$soImages = '~]* />~';
preg_match_all( $soImages, $soContent, $thePics );
$allPics = count($thePics[0]);
dump($thePics);
if( $allPics> 0 ){
echo $thePics[0][0]; //获取的整个Img属性
} else {
echo "没有图片";
}
//**************
$soImages = '~]* />~';
$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("//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提取文章HTML源码中首张图示路径
该功能通过PHP结合正则表达式完成,旨在获取文章HTML内的第一张图链接。代码仅作演示用途,实际项目中可根据需求扩展以提取所有图片URL。
// 注意这个变量中img标签末尾的细节变化
$str='
';
echo get_html_first_imgurl($str);
exit;
/**
* 获取文章内容html中第一张图片地址
*/
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开发过程中提供实用价值。