从HTML标记中删除样式属性 [英] Remove style attribute from HTML tags
问题描述
我对正则表达式不太满意,但是对于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>
.
我该如何使用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 >
",直到我们进入space
和style="..."
部分. /i
使它甚至可以与STYLE="..."
一起使用.用捕获的组$1
替换此匹配项.如果标签不包含style="..."
,则会保留该标签.
Match a <
followed by one or more "not >
" until we come to space
and the 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屋!