Heim  >  Artikel  >  Backend-Entwicklung  >  求个HTML替换正则

求个HTML替换正则

WBOY
WBOYOriginal
2016-06-06 20:34:421082Durchsuche

需求这样的。

有一个富文本编辑器,提交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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn