簡體   English   中英

如何使用正則表達式從HTML剝離屬性(樣式屬性除外)?

[英]How do I strip attributes (except the style attribute) from HTML using regular expressions?

原始代碼:

<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);

任何人都可以幫助我解決這個問題? 謝謝!!

不推薦使用正則表達式,但這可能有效。

編輯:固定選項組,在錯誤的位置。

此處的測試用例: 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'

目前沒有可用的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的regex支持它,並且可以在多行模式下運行,則可以用空格速記代替那些[\\ t \\ r \\ n])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM