2010-03-07 97 views
1

我需要一個乾淨而簡單的腳本,它可以查找和刪除字符串中所有html標籤的所有事件屬性。 「關於...」屬性是 - 鼠標點擊,等的onkeyup從標籤中刪除事件屬性

編輯:這裏是他們如何做到在Kohana中:

$string = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $string); 

編輯:這裏是他們如何做到這一點的笨:

$string = preg_replace("#<([^><]+?)([^a-z_\-]on\w*|xmlns)(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $string); 
+0

您不關心已經以編程方式添加的事件偵聽器嗎? – Robusto 2010-03-07 02:25:16

+0

在當前情況下不關心這一點。 – 2010-03-07 02:31:24

回答

2

該函數需要4個參數。

  1. $ msg。您要從中剝離屬性的文本。
  2. $ tag。您想從中剝離屬性的標籤(例如,p)。
  3. $ attr。一個數組,其中包含要剝離的屬性的名稱(其餘部分完好無損)。如果數組爲空,則該函數將剝離所有屬性。
  4. $後綴。附加到標籤的可選文本。例如,它可能是一個新的屬性。

Stripping Tag Attributes from HTML code兩者在這裏筆者職位代碼,我從我的回答省略它,因爲它是漫長的,不想要求代碼的所有權。

希望這是你在找什麼。

1

你可以做這行的東西:

<?php 

$html = '<p class="foo" onclick="bar()"> 
    Lorem ipsum dolor sit amet, consectetur <em>adipisicing elit</em>, 
    sed do eiusmod tempor incididunt ut labore 
    <a href="http://www.google.es" onmouseover="mover()" onmouseout="mout()" title="Google">et dolore magna aliqua</a>. 
    t enim ad minim veniam.</p> 
'; 

$doc = new DOMDocument; 
$doc->loadHTML($html); 

echo "Before:\n" . $doc->saveHTML() . "\n"; 

foreach($doc->getElementsByTagName('*') as $node){ 
    $remove = array(); 
    foreach($node->attributes as $attributeName => $attribute){ 
     if(substr($attributeName, 0, 2)=='on'){ 
      $remove[] = $attributeName; 
     } 
    } 
    foreach($remove as $i){ 
     $node->removeAttribute($i); 
    } 
} 

echo "After:\n" . $doc->saveHTML() . "\n"; 

?> 

這是隻是一個想法。它需要進行一些調整,因爲它會添加標籤來將HTML片段轉換爲完整文檔,但您可以將其用作起點。