2009-04-20 149 views

回答

14

雖然有更好的方法,你實際上可以剝去HTML標籤參數使用正則表達式:

<?php 
function stripArgumentFromTags($htmlString) { 
    $regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; // match any start tag 

    $chunks = preg_split($regEx, $htmlString, -1, PREG_SPLIT_DELIM_CAPTURE); 
    $chunkCount = count($chunks); 

    $strippedString = ''; 
    for ($n = 1; $n < $chunkCount; $n++) { 
     $strippedString .= $chunks[$n]; 
    } 

    return $strippedString; 
} 
?> 

上面也許可以在更少的字符寫的,但它的工作(快速和骯髒的) 。

-1

你也可以看看html淨化器。誠然,它非常臃腫,如果它只是想象這個具體的例子,它可能不適合你的需求,但它或多或少地爲可能的敵對html提供「防彈」淨化。你也可以選擇允許或禁止某些屬性(它是高度可配置的)。

http://htmlpurifier.org/

9

地帶屬性(在PHP5標準)使用SimpleXML

<?php 

// define allowable tags 
$allowable_tags = '<p><a><img><ul><ol><li><table><thead><tbody><tr><th><td>'; 
// define allowable attributes 
$allowable_atts = array('href','src','alt'); 

// strip collector 
$strip_arr = array(); 

// load XHTML with SimpleXML 
$data_sxml = simplexml_load_string('<root>'. $data_str .'</root>', 'SimpleXMLElement', LIBXML_NOERROR | LIBXML_NOXMLDECL); 

if ($data_sxml) { 
    // loop all elements with an attribute 
    foreach ($data_sxml->xpath('descendant::*[@*]') as $tag) { 
     // loop attributes 
     foreach ($tag->attributes() as $name=>$value) { 
      // check for allowable attributes 
      if (!in_array($name, $allowable_atts)) { 
       // set attribute value to empty string 
       $tag->attributes()->$name = ''; 
       // collect attribute patterns to be stripped 
       $strip_arr[$name] = '/ '. $name .'=""/'; 
      } 
     } 
    } 
} 

// strip unallowed attributes and root tag 
$data_str = strip_tags(preg_replace($strip_arr,array(''),$data_sxml->asXML()), $allowable_tags); 

?> 
+0

這個偉大的工程,只不過如果你的輸入html格式正確的話就是xml。否則,在分析之前,您必須對輸入html進行一些預清理。如果你不完全控制源html輸入,這可能是非常繁瑣的消毒。 – 2015-08-18 04:20:24

7

這是一個功能,可以讓你去除所有的屬性,除了那些你想:

function stripAttributes($s, $allowedattr = array()) { 
    if (preg_match_all("/<[^>]*\\s([^>]*)\\/*>/msiU", $s, $res, PREG_SET_ORDER)) { 
    foreach ($res as $r) { 
    $tag = $r[0]; 
    $attrs = array(); 
    preg_match_all("/\\s.*=(['\"]).*\\1/msiU", " " . $r[1], $split, PREG_SET_ORDER); 
    foreach ($split as $spl) { 
     $attrs[] = $spl[0]; 
    } 
    $newattrs = array(); 
    foreach ($attrs as $a) { 
     $tmp = explode("=", $a); 
     if (trim($a) != "" && (!isset($tmp[1]) || (trim($tmp[0]) != "" && !in_array(strtolower(trim($tmp[0])), $allowedattr)))) { 

     } else { 
      $newattrs[] = $a; 
     } 
    } 
    $attrs = implode(" ", $newattrs); 
    $rpl = str_replace($r[1], $attrs, $tag); 
    $s = str_replace($tag, $rpl, $s); 
    } 
    } 
    return $s; 
} 

在示例它會是:

echo stripAttributes('<p class="one" otherrandomattribute="two">'); 

或如果你例如。要保持「class」屬性:

echo stripAttributes('<p class="one" otherrandomattribute="two">', array('class')); 

或者

假設你將消息發送到收件箱和你CKEDITOR組成你的消息,你可以如下分配功能,並將它顯示給$ message變量在發送之前。請注意,名稱爲stripAttributes()的函數將去掉所有不必要的html標籤。我試過了,它工作正常。我只看到了我加入的格式,如粗體e.t.c.

$message = stripAttributes($_POST['message']); 

或 可以echo $message;預覽。

5

我誠實地認爲唯一的方法是使用標籤屬性白名單與HTML Purifier庫。示例腳本這裏:

<html><body> 

<?php 

require_once '../includes/htmlpurifier-4.5.0-lite/library/HTMLPurifier/Bootstrap.php'; 
spl_autoload_register(array('HTMLPurifier_Bootstrap', 'autoload')); 

$config = HTMLPurifier_Config::createDefault(); 
$config->set('HTML.Allowed', 'p,b,a[href],i,br,img[src]'); 
$config->set('URI.Base', 'http://www.example.com'); 
$config->set('URI.MakeAbsolute', true); 

$purifier = new HTMLPurifier($config); 

$dirty_html = " 
    <a href=\"http://www.google.de\">broken a href link</a 
    fnord 

    <x>y</z> 
    <b>c</p> 
    <script>alert(\"foo!\");</script> 

    <a href=\"javascript:alert(history.length)\">Anzahl besuchter Seiten</a> 
    <img src=\"www.example.com/bla.gif\" /> 
    <a href=\"http://www.google.de\">missing end tag 
ende 
"; 

$clean_html = $purifier->purify($dirty_html); 

print "<h1>dirty</h1>"; 
print "<pre>" . htmlentities($dirty_html) . "</pre>"; 

print "<h1>clean</h1>"; 
print "<pre>" . htmlentities($clean_html) . "</pre>"; 

?> 

</body></html> 

我們得到以下的清潔,符合標準的HTML片段:

<a href="http://www.google.de">broken a href link</a>fnord 

y 
<b>c 
<a>Anzahl besuchter Seiten</a> 
<img src="http://www.example.com/www.example.com/bla.gif" alt="bla.gif" /><a href="http://www.google.de">missing end tag 
ende 
</a></b> 

在你的情況下,白名單是:

$config->set('HTML.Allowed', 'p');