* trimscript.php

<?php

/**
 * xss过滤
 * @param $str string
 * @return string
 */
function trim_script($str) {
    $str = preg_replace('/\\<([\\/]?)script([^\\>]*?)\\>/si', '&lt;\\1script\\2&gt;', $str);
    $str = preg_replace('/\\<([\\/]?)iframe([^\\>]*?)\\>/si', '&lt;\\1iframe\\2&gt;', $str);
    $str = preg_replace('/\\<([\\/]?)frame([^\\>]*?)\\>/si', '&lt;\\1frame\\2&gt;', $str);
    return str_replace('javascript:', 'javascript:', $str);
}

// 测试代码:

$s = "<script>alert(1)</script>";
printf("%s\n", trim_script($s));

 

$ php trimscript.php

&lt;script&gt;alert(1)&lt;/script&gt;

 

* remove_xss.php

function remove_xss($string)
{
	$string = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]+/S', '', $string);
	$parm1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	$parm2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	$parm = array_merge($parm1, $parm2);

	for ($i = 0; $i < sizeof($parm); $i++) {
		$pattern = '/';

		for ($j = 0; $j < strlen($parm[$i]); $j++) {
			if (0 < $j) {
				$pattern .= '(';
				$pattern .= '(&#[x|X]0([9][a][b]);?)?';
				$pattern .= '|(&#0([9][10][13]);?)?';
				$pattern .= ')?';
			}

			$pattern .= $parm[$i][$j];
		}

		$pattern .= '/i';
		$string = preg_replace($pattern, ' ', $string);
	}

	return $string;
}