1 详情中的数据转化
function replaceImgUrl($content = ‘‘, $strUrl = ‘‘) { if($content==‘‘) { return $content; } if($strUrl==‘‘) { $strUrl=cur_domain(); } //提取图片路径的src的正则表达式 并把结果存入$matches中 preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches); // <img src="/upload/ueditor/20200911/1599820608507775.png" title="1599820608507775.png" alt="area_adv.png"/> $img = ""; if(!empty($matches)) { //注意,上面的正则表达式说明src的值是放在数组的第三个中 $img = $matches[2]; }else { $img = ""; } //视频 preg_match_all("/<video(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches2); if(!empty($matches2)) { //注意,上面的正则表达式说明src的值是放在数组的第三个中 $img2 = $matches2[2]; } $img=array_merge($img,$img2); // dump($img); if (!empty($img)) { $patterns= array(); $replacements = array(); foreach($img as $imgItem){ $final_imgUrl = $strUrl.$imgItem; $replacements[] = $final_imgUrl; $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/"; $patterns[] = $img_new; } //让数组按照key来排序 ksort($patterns); ksort($replacements); //替换内容 $vote_content = preg_replace($patterns, $replacements, $content); return $vote_content; }else { return $content; } }
2 获取文章的第一张图片
function get_html_first_imgurl($html){ $pattern = "/<[img|IMG].*?src=[\‘|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\‘|\"].*?[\/]?>/"; preg_match_all($pattern, $html, $matches);//正则表达式把图片的整个都获取出来了 // dump($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; }
原文:https://www.cnblogs.com/exo5/p/13689369.html