如何使用正则表达式从HTML中删除属性(样式属性除外)?

时间:2012-04-15 15:55:45

标签: php html regex

原始代码:

<div style="height:100px;" id="main" >
<a href="133"></a>
<blockquote color="123">

替换后

<div style="height:100px;" >
<a></a>
<blockquote>

我尝试使用正则表达式,但它不起作用

preg_replace('#<(div|span|a|img|ul|li|blockquote).*( style=".*")?(.*)>#Us', '<$1$2>', $content);
谁能帮我解决这个问题?谢谢!!

2 个答案:

答案 0 :(得分:1)

不推荐正则表达式,但这可能有效。

编辑:固定选项组,是在错误的地方。

此处的测试用例:http://ideone.com/vRk1u

'~
( < (?:div|span|a|img|ul|li|blockquote) (?=\s) )         # 1
   (?= 
     (?:
        (?:[^>"\']|"[^"]*"|\'[^\']*\')*? 
        (                                                      # 2
          \s  style \s*=
          (?: (?>  \s* ([\'"]) \s* (?:(?!\g{-1}) .)* \s* \g{-1} )  #3
            | (?>  (?!\s*[\'"]) \s* [^\s>]* (?=\s|>) )
          )
        )
     )?
   )
  \s* (?:".*?"|\'.*?\'|[^>]*?)+ 
( /?> )                                                  # 4
~xs'

答案 1 :(得分:0)

此刻我没有PHP,所以我会给你写一个关于Javascript的正则表达式,你可以轻松移植它。 (我将使用RegExp对象,因此已经为您引用了正则表达式)

'<div style="height:100px;" id="main" >'.replace(new RegExp('<([a-zA-Z0-9]*)(.*([ \t\r\n]style[ \t\r\n]*=[ \t\r\n]*(("[^"]*")|(\'[^\']*\'))))*[^>]*>'), '<$1$3>')
 == <div style="height:100px;">

'<div style=\'height:100px;\' id="main" >'.replace(new RegExp('<([a-zA-Z0-9]*)(.*([ \t\r\n]style[ \t\r\n]*=[ \t\r\n]*(("[^"]*")|(\'[^\']*\'))))*[^>]*>'), '<$1$3>')
 == <div style='height:100px;'>

'<div style="height:100px;">'.replace(new RegExp('<([a-zA-Z0-9]*)(.*([ \t\r\n]style[ \t\r\n]*=[ \t\r\n]*(("[^"]*")|(\'[^\']*\'))))*[^>]*>'), '<$1$3>')
 == <div style="height:100px;">

'<div dfg dfg fdg>'.replace(new RegExp('<([a-zA-Z0-9]*)(.*([ \t\r\n]style[ \t\r\n]*=[ \t\r\n]*(("[^"]*")|(\'[^\']*\'))))*[^>]*>'), '<$1$3>')
 == <div>

'<div>'.replace(new RegExp('<([a-zA-Z0-9]*)(.*([ \t\r\n]style[ \t\r\n]*=[ \t\r\n]*(("[^"]*")|(\'[^\']*\'))))*[^>]*>'), '<$1$3>')
 == <div>

所以它的一个正则表达式考虑了大多数可能的情况。

这会回答你的问题吗?

(顺便说一下,如果php的正则表达式支持它并且它可以在多行模式下工作,你可以用空白速记替换那些[\ t \ r \ n])