百度在2016年底推出了mip,具体可以百度搜索下是个什么情况,本代码是基于php实现的内容替换方法,不仅限于phpcms,任何其他cms都可以用.
注意仅仅是替换正文内容(标题也行)的,不是整套的模板解决方案哦.
伦理片 http://www.dotdy.com/
- <?php
- /**
- * 百度mip内容标准替换方法
- *
- * @author yunbinbai@foxmail.com for http://www.soyiyuan.com/city/
- * @createtime 2017-1-11
- * @modifytime
- * @param string $content 待转换的内容正文
- * @return string
- */
- function mip_replace($content = ''){
- $pattern1 = "#<img.*?src=['\"](.*?)['\"].*?>#ims";
- $imgcontent=array();
- preg_match_all($pattern1,$content,$img);
- $imgcontent = $img[0];
- $imgurl = $img[1];
- foreach($imgcontent as $imgk=>$imgv)
- {
- $temp = str_replace('<img','mip-img',$imgv);
- $temp = str_replace('/>','></mip-img',$temp);
- $url = $imgurl[$imgk];
- $url = mip_format_img_url($url);
- $temp = preg_replace("/src=['\"].*?['\"]/si","src=\"$url\"",$temp);
- $mipimg[$imgk] = $temp;
- }
- $content = preg_replace($imgcontent,$mipimg,$content);
- $content =preg_replace("/<a /si","<a target=\"_blank\" ",$content);
- $content =preg_replace("/style=\".*?\"/si","",$content);
- return mip_utf8($content);
- }
- function mip_format_img_url( $url = ''){
- if(stripos($url, 'http') === 0 || stripos($url, 'ftp') === 0 ){
- return $url;
- }
- if(stripos($url, '/') === 0){
- $url = 'http://'.$_SERVER['HTTP_HOST'].$url;
- }else{
- $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$url;
- }
- return $url;
- }
- function mip_utf8($string = '') {
- $fileType = mb_detect_encoding($string , array('UTF-8','GBK','LATIN1','BIG5'));
- if( $fileType != 'UTF-8'){
- $string = mb_convert_encoding($string ,'utf-8' , $fileType);
- }
- return $string;
- }
- ?>
本代码考虑了编码问题,针对图片/样式等进行了替换,符合百度对mip的规范要求,有任何问题的可以跟帖说明.
使用方法:以上代码直接放到公共全局文件,或者模板里都行,
然后调用 mip_replace($content) ,变量$content根据你模板定义的来.