php处理html中的所有img标签的尺寸宽度让其自适应类比js和uniapp

尤其是我们在vue中的html,如果里面包含图片的话经常出现撑破和显示不全的情况,用同样的思路对html代码进行替换即可。

下面是php的代码,js的自己照着先琢磨,写到了再更新

function fixImgSizeAll($html){
	$html = preg_replace_callback(
		'/<img.*?>/i',
		function ($matches){
			if($matches && isset($matches[0])){
				return fixImgSize($matches[0]);
			}
		},
		$html
	);
	return $html;
}

//让图片自适应宽度
function fixImgSize($img){
	//剔除width属性
	$img = preg_replace_callback(
		'/width="\d*"/i',
		function ($matches){
			if($matches && isset($matches[0]))
				return 'width="auto"';
		},
		$img);
	//剔除height属性
	$img = preg_replace_callback(
		'/height="\d*"/i',
		function ($matches){
			if($matches && isset($matches[0]))
				return '';
		},
		$img);
	//去style中的width
	$img = preg_replace_callback(
		'/width:\d*px;/i',
		function ($matches){
			if($matches && isset($matches[0]))
				return 'max-width:100%;';
		},
		$img);
	//去style中的height
	$img = preg_replace_callback(
		'/height:\d*px;/i',
		function ($matches){
			if($matches && isset($matches[0]))
				return 'height:auto;';
		},
		$img);

	if(stripos($img,'width') === false){
		//本身就没有width设置,强制不超出100%
		if(stripos($img,' style=') === false){
			//没有设置style样式,直接添加
			$img = str_ireplace('<img','<img style="max-width:100%"',$img);
		}else{
			//有设置style样式,修改
			//style=''
			$img = preg_replace_callback(
				'/style=\'(.*?)\'/i',
				function ($matches){
					if($matches && isset($matches[1])){
						$style = "max-width:100%;" . $matches[1];
						return 'style=\''. $style .'\'';
					}
				},
				$img);
			//style=""
			$img = preg_replace_callback(
				'/style="(.*?)"/i',
				function ($matches){
					if($matches && isset($matches[1])){
						$style = "max-width:100%;" . $matches[1];
						return 'style="'. $style .'"';
					}
				},
				$img);
		}
	}
	return $img;
}

直接调用

fixImgSizeAll('你的html内容');

即可