基于phpcms的百度mip内容转换方法(适用任何cms)

百度在2016年底推出了mip,具体可以百度搜索下是个什么情况,本代码是基于php实现的内容替换方法,不仅限于phpcms,任何其他cms都可以用.

注意仅仅是替换正文内容(标题也行)的,不是整套的模板解决方案哦.

 伦理片 http://www.dotdy.com/ 

Php代码   收藏代码
  1. <?php  
  2. /** 
  3.  * 百度mip内容标准替换方法 
  4.  * 
  5.  * @author yunbinbai@foxmail.com for http://www.soyiyuan.com/city/ 
  6.  * @createtime 2017-1-11 
  7.  * @modifytime 
  8.  * @param string $content 待转换的内容正文 
  9.  * @return string 
  10.  */  
  11. function mip_replace($content = ''){  
  12.     $pattern1 = "#<img.*?src=['\"](.*?)['\"].*?>#ims";  
  13.         $imgcontent=array();  
  14.         preg_match_all($pattern1,$content,$img);  
  15.         $imgcontent = $img[0];  
  16.         $imgurl = $img[1];  
  17.         foreach($imgcontent as $imgk=>$imgv)  
  18.         {  
  19.           $temp =  str_replace('<img','mip-img',$imgv);  
  20.           $temp = str_replace('/>','></mip-img',$temp);  
  21.           $url = $imgurl[$imgk];  
  22.           $url = mip_format_img_url($url);  
  23.   
  24.           $temp = preg_replace("/src=['\"].*?['\"]/si","src=\"$url\"",$temp);  
  25.           $mipimg[$imgk] = $temp;  
  26.         }  
  27.   
  28.         $content = preg_replace($imgcontent,$mipimg,$content);  
  29.         $content =preg_replace("/<a /si","<a target=\"_blank\" ",$content);  
  30.         $content =preg_replace("/style=\".*?\"/si","",$content);  
  31.           
  32.         return mip_utf8($content);  
  33.           
  34. }  
  35.   
  36.         function mip_format_img_url( $url = ''){  
  37.             if(stripos($url'http') === 0 || stripos($url'ftp') === 0 ){  
  38.                 return $url;  
  39.             }  
  40.             if(stripos($url'/') === 0){  
  41.                 $url = 'http://'.$_SERVER['HTTP_HOST'].$url;  
  42.             }else{  
  43.                 $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$url;  
  44.             }  
  45.             return $url;  
  46.         }  
  47.   
  48.   
  49.   
  50.             function mip_utf8($string = '') {  
  51.   
  52.                 $fileType = mb_detect_encoding($string , array('UTF-8','GBK','LATIN1','BIG5'));  
  53.                 if$fileType != 'UTF-8'){  
  54.                     $string = mb_convert_encoding($string ,'utf-8' , $fileType);  
  55.                 }  
  56.                 return $string;  
  57.             }  
  58. ?>  

 

本代码考虑了编码问题,针对图片/样式等进行了替换,符合百度对mip的规范要求,有任何问题的可以跟帖说明.

使用方法:以上代码直接放到公共全局文件,或者模板里都行,

然后调用 mip_replace($content) ,变量$content根据你模板定义的来.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值