Home > Backend Development > PHP Tutorial > 求个HTML替换正则

求个HTML替换正则

WBOY
Release: 2016-06-06 20:34:42
Original
1124 people have browsed it

需求这样的。

有一个富文本编辑器,提交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>
Copy after login
Copy after login

这正则该咋写

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

回复内容:

需求这样的。

有一个富文本编辑器,提交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>
Copy after login
Copy after login

这正则该咋写

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

如果只是把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>
Copy after login

<code><?php $dom = new DOMDocument();
$dom->loadHTML('xxx');
$element = $dom->getElementsByTagName('img')[0]; //需要循环
$element->setAttribute('width', "100%");
$dom->saveHTML();
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template