php js正则 解决 详情页图片超出问题 匹配img标签内容追加style样式,给富文本中的图片设置大小和居中显示
  VPt5meHeWcfY 2023年11月02日 43 0

做小程序或手机端经常会遇到商品详情,文章详情里带图片的从别的地方复制过来带着样式,导致超出屏幕显示不全的问题

php解决

function format_img($content,$style=''){
    if(empty($style))$style = 'max-width:100%;height:auto;';
    $content= preg_replace("/(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)/i", "$1 style=\"\"$2" , $content); 
    return preg_replace("/(\<img.*?style=['\"])([^\>]+\>)/i", "$1".$style."$2" , $content); 
}

Js解决


function format_img(htmlstr){
	//正则匹配不含style="" 或 style='' 的img标签
	var regex1 = new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)","gmi");
	//给不含style="" 或 style='' 的img标签加上style=""
	htmlstr = htmlstr.replace(regex1, "$2 style=\"\"$3");
        //正则匹配含有style的img标签
	var regex2 = new RegExp("(i?)(\<img.*?style=['\"])([^\>]+\>)","gmi");
	htmlstr = htmlstr.replace(regex2, "$2max-width:100%;height:auto;border:5px solid red;$3");
	return htmlstr;
}

还有一种比较变态的做法是直接用正则表达式删除img标签的width、height、style


<?php
$txt1='<a href="https://blog.bitefu.net/post/501.html" style="margin:0 auto;border-radius:6px; background-color: #ffb808;display: block;text-align: center;padding: 12px 12px 12px 12px;color:#fff; width: 180px;font-weight: bold;">查看历史中奖记录</a><img src="http://www.baidu.com/Uploads/ueditor/image/20170512/1494556977462196.jpg" title="1494556977462196.jpg" alt="timg.jpg" style="width: 524px; height: 689px;" width="524" height="689"><img src="http://www.baidu.com/Uploads/ueditor/image/20170512/1494556977462196.jpg" title="1494556977462196.jpg" alt="timg.jpg" style="width: 524px; height: 689px;" width="524" height="689">';
$txt1 = preg_replace( '/(<img.*?)(style=.+?[\'|"])|((width)=[\'"]+[0-9]+[\'"]+)|((height)=[\'"]+[0-9]+[\'"]+)/i', '$1' , $txt1); 
echo $txt1;
?>
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  NHaurzrhyr04   2023年12月23日   105   0   0 htmljQueryhtmljQuery
  BEOpup9HILHT   2023年12月23日   79   0   0 htmljQueryhtmljQuery
VPt5meHeWcfY