Baidu mip content conversion method based on phpcms (applicable to any cms)

Baidu launched mip at the end of 2016, what is the situation under Baidu search, this code is a content replacement method based on php, not limited to phpcms, any other cms can be used.

Note that it only replaces the body content (the title is also OK), not a complete template solution.

 

<?php
/**
 * Baidu mip content standard replacement method
 *
 * @author [email protected] for http://www.soyiyuan.com/city/
 * @createtime 2017-1-11
 * @modifytime
 * @param string $content The content body to be converted
 * @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;
			}
?>

 

This code considers the coding problem, and replaces the pictures/styles, etc., and meets Baidu's specification requirements for mip. If you have any questions, you can post it.

How to use: The above code can be placed directly in the public global file, or in the template,

Then call mip_replace($content) , the variable $content is defined according to your template.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326446302&siteId=291194637