增加外部链接判断 2020.09.22

  1. 判断是否是外部链接
  2. 详情中的数据转化
  3. 获取文章的第一张图片
  4. 对图片添加链接

判断是否是外部链接

 1 //true:不是   false:是  
 2     function is_httporhttps($field)
 3     {
 4         $return=false;
 5         if($field!='' && !preg_match('/(http:\/\/)|(https:\/\/)/i', $field))
 6         {
 7             $return=true;
 8         }
 9         return $return;
10     }

 

详情中的数据转化

 1 function replaceImgUrl($content = '', $strUrl = '')
 2 {
 3     if($content=='')
 4     {
 5         return $content;
 6     }
 7     if($strUrl=='')
 8     {
 9         $strUrl=cur_domain();
10     }
11     //提取图片路径的src的正则表达式 并把结果存入$matches中
12     preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches);
13 //    <img src="/upload/ueditor/20200911/1599820608507775.png" title="1599820608507775.png" alt="area_adv.png"/>
14     $img = "";
15     if(!empty($matches)) {
16         //注意,上面的正则表达式说明src的值是放在数组的第三个中
17         $img = $matches[2];
18     }else {
19         $img = "";
20     }
21 
22     //视频
23     preg_match_all("/<video(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches2);
24 
25     if(!empty($matches2)) {
26         //注意,上面的正则表达式说明src的值是放在数组的第三个中
27         $img2 = $matches2[2];
28     }
29 
30     $img=array_merge($img,$img2);
31 //    dump($img);
32 
33 
34     if (!empty($img)) {
35         $patterns= array();
36         $replacements = array();
37         foreach($img as $imgItem){
38             $final_imgUrl=$imgItem;
39             if(is_httporhttps($imgItem)){
40                 $final_imgUrl = $strUrl.$imgItem;
41             }
42             $replacements[] = $final_imgUrl;
43             $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
44             $patterns[] = $img_new;
45         }
46 
47 
48         //让数组按照key来排序
49         ksort($patterns);
50         ksort($replacements);
51 
52         //替换内容
53         $vote_content = preg_replace($patterns, $replacements, $content);
54         return $vote_content;
55     }else {
56         return $content;
57     }
58 }

 

获取文章的第一张图片

 1 function get_html_first_imgurl($html){
 2     $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/";
 3     preg_match_all($pattern, $html, $matches);//正则表达式把图片的整个都获取出来了
 4 //    dump($matches);
 5     $img_arr = $matches[0];//全部图片数组
 6     $first_img_url = "";
 7     if (!empty($img_arr)) {
 8         $first_img = $img_arr[0];
 9         $p="#src=('|\")(.*)('|\")#isU";//正则表达式
10         preg_match_all ($p, $first_img, $img_val);
11         if(isset($img_val[2][0])){
12             $first_img_url = $img_val[2][0]; //获取第一张图片地址
13         }
14     }
15     return $first_img_url;
16 }

 

对图片添加链接

function str_imgurl($img='')
{
    if($img!='' && is_httporhttps($img))
    {
        $img='http://'.$_SERVER['HTTP_HOST'].$img;
    }
    return $img;
}

 

posted on 2020-09-18 09:19  思君邪  阅读(188)  评论(0编辑  收藏  举报