小编最近对网站手机版进行mip改造,根据mip的要求,不允许有内连的style,那么之前的直接输出文章内容肯定是不符合要求的,还有一个img标签也不支持,要改造成mip-img,知道原理了也简单,就是字符串的过滤,这个要求对正则表达式熟悉,现在就体现到开源系统的好处了,用的人多。网上肯定有答案,不过就是花时间去找,去核对。小编已经为大家整理好了
找到文件/phpcms/modules/wap/functions/global.func.php
然后加入字符串过滤,小编提供2种方式
方式一
<?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; } ?>
方式2
/** * mip内容图片替换 */ function content_mip($content) { $content = preg_replace('/<img[^>]*src=[\'"]?([^>\'"\s]*)[\'"]?[^>]*>/ie', "'<mip-img data-carousel=\"carousel\" class=\"mip-element mip-img\" src=\"$1\"></mip-img>'", $content); //匹配替换过的图片 $content = preg_replace("/style=.+?['|\"]/i",'',$content); return $content; }
小编偏向方式2,小编发现不是站内的图片 方式一不能替换img标签,方式2可以,虽然方式1感觉代码写的更6,各位代码大神可以在原基础上扩展完善。
然后页面输出
{mip_replace($rs['content'])}
就可以看到标准的mip格式啦,是不是棒棒哒。附上检测网址https://www.mipengine.org/validator/validate