首页  >  文章  >  后端开发  >  求个HTML替换正则

求个HTML替换正则

WBOY
WBOY原创
2016-06-06 20:34:421080浏览

需求这样的。

有一个富文本编辑器,提交html,内部会有图片内容。要求把所有img标签的width都设置为100%。而img标签的属性顺序都不一样。比如:

<code class="html"><img  src=""    style="max-width:90%" alt="求个HTML替换正则" >
<img     style="max-width:90%" src="" alt="求个HTML替换正则" >
<img     style="max-width:90%"  src="" alt="求个HTML替换正则" >
<img     style="max-width:90%" src="" alt="求个HTML替换正则" ></code>

这正则该咋写

<code class="php">return preg_replace_callback('/???/',function($match}{
},$html);</code>

回复内容:

需求这样的。

有一个富文本编辑器,提交html,内部会有图片内容。要求把所有img标签的width都设置为100%。而img标签的属性顺序都不一样。比如:

<code class="html"><img  src=""    style="max-width:90%" alt="求个HTML替换正则" >
<img     style="max-width:90%" src="" alt="求个HTML替换正则" >
<img     style="max-width:90%"  src="" alt="求个HTML替换正则" >
<img     style="max-width:90%" src="" alt="求个HTML替换正则" ></code>

这正则该咋写

<code class="php">return preg_replace_callback('/???/',function($match}{
},$html);</code>

如果只是把img的宽度设置成100%的话,那直接样式控制就行啦~哪里用着正则呢~
如果是担心有行内的样式的话,可以给样式加!important

赞成 @YuanWing 和 @leandre 同学的答案。
btw,顺便写了个 js 版的正则,php的话应该也差不多吧。
btw2,编辑器预览和最终暂时效果还不一样。。。

<code>javascript</code><code>var html = '

<div width="100px">
<img     style="max-width:90%" alt="求个HTML替换正则" ><img     style="max-width:90%" alt="求个HTML替换正则" ><img     style="max-width:90%" src="" alt="求个HTML替换正则" ><img  src=""    style="max-width:90%" alt="求个HTML替换正则" ><img     style="max-width:90%" src="" alt="求个HTML替换正则" >
</div>

';

html.replace(/(<img  alt="求个HTML替换正则" >]*?)(\s*)(width=[^\s\/\>]+)/g, function (str, m1, m2, m3) {
    return (m1 + m2 + 'width="100%"');
});
</code>

<code><?php $dom = new DOMDocument();
$dom->loadHTML('xxx');
$element = $dom->getElementsByTagName('img')[0]; //需要循环
$element->setAttribute('width', "100%");
$dom->saveHTML();
</code>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn