从 HTML 标签中删除样式属性 [英] Remove style attribute from HTML tags

查看:42
本文介绍了从 HTML 标签中删除样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太擅长正则表达式,但是对于 PHP,我想从 TinyMCE 返回的字符串中的 HTML 标记中删除 style 属性.

I'm not too good with regular expressions, but with PHP I'm wanting to remove the style attribute from HTML tags in a string that's coming back from TinyMCE.

因此将 <p style="...">Text</p> 更改为普通的 <p>Test</p>.

So change <p style="...">Text</p> to just vanilla <p>Test</p>.

我将如何使用 preg_replace() 函数来实现这一点?

How would I achieve this with something like the preg_replace() function?

推荐答案

实用的正则表达式 (<[^>]+) style=".*?" 将解决这个问题在所有合理的情况下.应该删除不是第一个捕获组的匹配部分,如下所示:

The pragmatic regex (<[^>]+) style=".*?" will solve this problem in all reasonable cases. The part of the match that is not the first captured group should be removed, like this:

$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $input);

匹配一个 < 后跟一个或多个not >";直到我们来到 spacestyle="..." 部分./i 使它在 STYLE="..." 的情况下也能工作.将此匹配替换为 $1,即捕获的组.如果标签不包含 style="...",它将保持原样.

Match a < followed by one or more "not >" until we come to space and the style="..." part. The /i makes it work even with STYLE="...". Replace this match with $1, which is the captured group. It will leave the tag as is, if the tag doesn't include style="...".

这篇关于从 HTML 标签中删除样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆