需求这样的。
有一个富文本编辑器,提交html,内部会有图片内容。要求把所有img标签的width都设置为100%。而img标签的属性顺序都不一样。比如:
<code class="html"></code>
这正则该咋写
<code class="php">return preg_replace_callback('/???/',function($match}{},$html);</code>
!本文来源gaodai.ma#com搞#代!码(网
搞gaodaima代码
回复内容:
需求这样的。
有一个富文本编辑器,提交html,内部会有图片内容。要求把所有img标签的width都设置为100%。而img标签的属性顺序都不一样。比如:
<code class="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></div>';html.replace(/(
<code><?php$dom = new DOMDocument();$dom->loadHTML('xxx');$element = $dom->getElementsByTagName('img')[0]; //需要循环$element->setAttribute('width', "100%");$dom->saveHTML();</code>