<?php // Safe HTML
// -------------
//
// Useful for "cleaning" form input that is to be
// viewed on a HTML page. Seems fairly safe, just
// enter the tags you want to allow in the
// $approvedtags array.
// Code originally from the PHP port of Slashdot:
// http://phplib.netuse.de/
//
// I needed this function for a forum I run, but
// couldn't find it anywhere. So I ended up
// extracting it from the phpslash code. I think
// it's useful for others as well, so I've made it
// available separately. I haven't made serious
// efforts of understanding the code, but it
// works!
//
// Gaute Hvoslef Kvalnes <ai98ghk@stud.hib.no>
//
// Usage: $text = safeHTML( $text );
function safeHTML($str)
{
$approvedtags = array(
"p"=>2, // 2 means accept all qualifiers: <foo bar>
"b"=>1, // 1 means accept the tag only: <foo>
"i"=>1,
"a"=>2,
"em"=>1,
"br"=>1,
"strong"=>1,
"blockquote"=>1,
"tt"=>1,
"hr"=>1,
"li"=>1,
"ol"=>1,
"ul"=>1
);
$str = stripslashes($str);
$str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>","<\1>",$str);
$str = eregi_replace("<a([^>]*)href="?([^"]*)"?([^>]*)>",
"<a href="\2">", $str);
$tmp = "";
while (eregi("<([^> ]*)([^>]*)>",$str,$reg))
{
$i = strpos($str,$reg[0]);
$l = strlen($reg[0]);
if ($reg[1][0] == "/")
$tag = strtolower(substr($reg[1],1));
else
$tag = strtolower($reg[1]);
if ($a = $approvedtags[$tag])
if ($reg[1][0] == "/")
$tag = "</$tag>";
elseif ($a == 1)
$tag = "<$tag>";
else
$tag = "<$tag " . $reg[2] . ">";
else
$tag = "";
$tmp .= substr($str,0,$i) . $tag;
$str = substr($str,$i+$l);
}
$str = $tmp . $str;
// Squash PHP tags unconditionally
$str = ereg_replace("<?","",$str);
return $str;
}
?>
|
|