백엔드 개발 PHP 튜토리얼 PHP에서 불법 및 특수 문자열을 필터링하는 방법

PHP에서 불법 및 특수 문자열을 필터링하는 방법

Jul 25, 2016 am 08:56 AM
PHP 문자열

在留言板中,有时需要对用户输入内容进行过滤,将一些非法与特殊字符串进行过滤处理,将其替换为*。下面本篇文章就来给大家分享一下过滤功能的实现代码,希望对大家有所帮助!

PHP에서 불법 및 특수 문자열을 필터링하는 방법

需求:用户在评论页面输入非法字符以后,需要将非法字符替换为*

简单实现方法:

1、index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>过滤留言板中的非法字符</title>  
<style type="text/css">  
<!--  
body {  
    margin-left: 0px;  
    margin-top: 0px;  
    margin-right: 0px;  
    margin-bottom: 0px;  
}  
-->  
</style></head>  
<body>  
<table width="1002" height="585" border="0" align="center" cellpadding="0" cellspacing="0">  
  <tr>  
    <td width="379" height="226"> </td>  
    <td width="445"> </td>  
    <td width="178"> </td>  
  </tr>  
     <form id="form1" name="form1" method="post" action="index_ok.php">  
  <tr>  
    <td height="260"> </td>  
    <td align="center" valign="top"><table width="430" border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#99CC67">  
      <tr>  
        <td width="81" height="30" align="right" bgcolor="#FFFFFF">发布主题:</td>  
        <td width="307" align="left" bgcolor="#FFFFFF"><input name="title" type="text" id="title" size="30" /></td>  
      </tr>  
      <tr>  
        <td align="right" bgcolor="#FFFFFF">发布内容:</td>  
        <td align="left" bgcolor="#FFFFFF"><textarea name="content" cols="43" rows="13" id="content"></textarea></td>  
      </tr>  
    </table></td>  
    <td> </td>  
  </tr>  
  <tr>  
    <td height="99"> </td>  
    <td align="center" valign="top"><table width="315" height="37" border="0" cellpadding="0" cellspacing="0">  
      <tr>  
        <td width="169" align="center"><input type="image" name="imageField" src="images/bg1.JPG" /></td>  
        <td width="146" align="center"><input type="image" name="imageField2" src="images/bg3.JPG" onclick="form.reset();return false;" /></td>  
      </tr>  
    </table></td>  
    <td> </td>  
  </tr>  
      </form>  
</table>  
</body>  
</html>
로그인 후 복사

2、index_ok.php

<?php   
$title=$_POST[title];  
$content=$_POST[content];  
$str="****";  
$titles = preg_replace("/(黑客)|(抓包)|(监听)/",$str,$title);  
$contents = preg_replace("/(黑客)|(抓包)|(监听)/",$str,$content);  
?>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>过滤留言板中的非法字符</title>  
<style type="text/css">  
<!--  
body {  
    margin-left: 0px;  
    margin-top: 0px;  
    margin-right: 0px;  
    margin-bottom: 0px;  
}  
.STYLE1 {  
    font-size: 12px;  
    color: #855201;  
}  
-->  
</style></head>  
<body>  
<table width="1002" height="585" border="0" align="center" cellpadding="0" cellspacing="0">  
  <tr>  
    <td width="400" height="226"> </td>  
    <td width="406"> </td>  
    <td width="196"> </td>  
  </tr>  
     <form id="form1" name="form1" method="post" action="index_ok.php">  
  <tr>  
    <td height="260"> </td>  
    <td align="left" valign="top"><p class="STYLE1">发布主题:<?php echo $titles;?></p>  
      <p class="STYLE1">发布内容:<?php echo $contents;?></p></td>  
    <td> </td>  
  </tr>  
  <tr>  
    <td> </td>  
    <td align="center" valign="top"> </td>  
    <td> </td>  
  </tr>  
  </form>  
</table>  
</body>  
</html>
로그인 후 복사

运行结果

PHP에서 불법 및 특수 문자열을 필터링하는 방법

复杂实现方法:可过滤JS 、PHP标签

  //简单过滤JS 、PHP标签
  function cleanJs($html){
  	$html=trim($html);
  	$html=str_replace(array(&#39;<?&#39;,&#39;?>&#39;),array(&#39;<?&#39;,&#39;?>&#39;),$html);
  	$pattern=array(
    "&#39;<script[^>]*?>.*?</script>&#39;si",
    "&#39;<style[^>]*?>.*?</style>&#39;si",
    "&#39;<frame[^>]*?>&#39;si",
    "&#39;<iframe[^>]*?>.*?</iframe>&#39;si",
    "&#39;<link[^>]*?>&#39;si"
    );
    $replace=array("","","","","");
    return	preg_replace($pattern,$replace,$html);
  }
  /* Remove JS/CSS/IFRAME/FRAME 过滤JS/CSS/IFRAME/FRAME/XSS等恶意攻击代码(可安全使用)
   * Return string
   */
  function cleanJsCss($html){
  	$html=trim($html);
  	$html=preg_replace(&#39;/\0+/&#39;, &#39;&#39;, $html);
	$html=preg_replace(&#39;/(\\\\0)+/&#39;, &#39;&#39;, $html);
	$html=preg_replace(&#39;#(&\#*\w+)[\x00-\x20]+;#u&#39;,"\\1;",$html);
	$html=preg_replace(&#39;#(&\#x*)([0-9A-F]+);*#iu&#39;,"\\1\\2;",$html);
	$html=preg_replace("/%u0([a-z0-9]{3})/i", "&#x\\1;", $html);
	$html=preg_replace("/%([a-z0-9]{2})/i", "&#x\\1;", $html);
  	$html=str_replace(array(&#39;<?&#39;,&#39;?>&#39;),array(&#39;<?&#39;,&#39;?>&#39;),$html);
    $html=preg_replace(&#39;#\t+#&#39;,&#39; &#39;,$html);
	$scripts=array(&#39;javascript&#39;,&#39;vbscript&#39;,&#39;script&#39;,&#39;applet&#39;,&#39;alert&#39;,&#39;document&#39;,&#39;write&#39;,&#39;cookie&#39;,&#39;window&#39;);
	foreach($scripts as $script){
		$temp_str="";
		for($i=0;$i<strlen($script);$i++){
			$temp_str.=substr($script,$i,1)."\s*";
		}
		$temp_str=substr($temp_str,0,-3);
		$html=preg_replace(&#39;#&#39;.$temp_str.&#39;#s&#39;,$script,$html);
		$html=preg_replace(&#39;#&#39;.ucfirst($temp_str).&#39;#s&#39;,ucfirst($script),$html);
	}
	$html=preg_replace("#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $html);
	$html=preg_replace("#<img .+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\ alt="PHP에서 불법 및 특수 문자열을 필터링하는 방법" >#si", "", $html);
	$html=preg_replace("#<(script|xss).*?\>#si", "<\\1>", $html);
	$html=preg_replace(&#39;#(<[^>]*?)(onblur|onchange|onclick|onfocus|onload|onmouseover|onmouseup|onmousedown|onselect|onsubmit|onunload|onkeypress|onkeydown|onkeyup|onresize)[^>]*>#is&#39;,"\\1>",$html);
	//$html=preg_replace(&#39;#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is&#39;, "<\\1\\2\\3>", $html);
	$html=preg_replace(&#39;#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is&#39;, "<\\1\\2\\3>", $html);
	$html=preg_replace(&#39;#(alert|cmd|passthru|eval|exec|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si&#39;, "\\1\\2(\\3)", $html);
	$bad=array(
	&#39;document.cookie&#39;	=> &#39;&#39;,
	&#39;document.write&#39;	=> &#39;&#39;,
	&#39;window.location&#39;	=> &#39;&#39;,
	"javascript\s*:"	=> &#39;&#39;,
	"Redirect\s+302"	=> &#39;&#39;,
	&#39;<!--&#39;				=> &#39;<!--&#39;,
	&#39;-->&#39;				=> &#39;-->&#39;
	);
	foreach ($bad as $key=>$val){
		$html=preg_replace("#".$key."#i",$val,$html);
	}
    return	$html;
  }
  //过滤html标签以及敏感字符

  function cleanHtml($html){
  	return cleanYellow(htmlspecialchars($html));
  }
  //过滤部分HTML标签

  function cleanFilter($html){
  	$html=trim($html);
  	$html=preg_replace("/<p[^>]*?>/is","<p>",$html);
  	$html=preg_replace("/<div[^>]*?>/is","<div>",$html);
  	$html=preg_replace("/<ul[^>]*?>/is","<ul>",$html);
  	$html=preg_replace("/<li[^>]*?>/is","<li>",$html);
  	$html=preg_replace("/<span[^>]*?/is","<span>",$html);
  	$html=preg_replace("/<a[^>]*?>(.*)?<\/a>/is","\${1}",$html);
  	$html=preg_replace("/<table[^>]*?>/is","<table>",$html);
  	$html=preg_replace("/<tr[^>]*?>/is","<tr>",$html);
  	$html=preg_replace("/<td[^>]*?>/is","<td>",$html);
  	$html=preg_replace("/<ol[^>]*?>/is","<ol>",$html);
  	$html=preg_replace("/<form[^>]*?>/is","",$html);
  	$html=preg_replace("/<input[^>]*?>/is","",$html);
  	return $html;
  }
  //过滤非法的敏感字符串
  function cleanYellow($txt){
  	$txt=str_replace(
  	array("黄色","性爱","做爱","我日","我草","我靠","尻","共产党","胡锦涛","毛泽东",
  	"政府","中央","研究生考试","性生活","色情","情色","我考","麻痹","妈的","阴道",
  	"淫","奸","阴部","爱液","阴液","臀","色诱","煞笔","傻比","阴茎","法轮功","性交","阴毛","江泽民"),
  	array("*1*","*2*","*3*","*4*","*5*","*6*","*7*","*8*","*9*","*10*",
  	"*11*","*12*","*13*","*14*","*15*","*16*","*17*","*18*","*19*","*20*",
  	"*21*","*22*","*23*","*24*","*25*","*26*","*27*","*28*","*29*","*30*","*31*","*32*","*33*","*34*"),
  	$txt);
  	return $txt;
  }
  //过滤敏感字符串以及恶意代码
  function cleanAll($html){
  	return cleanYellow(cleanJsCss($html));
  }
  //全半角字符替换
  function setFilter($html){
  		$arr=array(&#39;0&#39; => &#39;0&#39;, &#39;1&#39; => &#39;1&#39;, &#39;2&#39; => &#39;2&#39;, &#39;3&#39; => &#39;3&#39;, &#39;4&#39; => &#39;4&#39;,
                 &#39;5&#39; => &#39;5&#39;, &#39;6&#39; => &#39;6&#39;, &#39;7&#39; => &#39;7&#39;, &#39;8&#39; => &#39;8&#39;, &#39;9&#39; => &#39;9&#39;,
                 &#39;A&#39; => &#39;A&#39;, &#39;B&#39; => &#39;B&#39;, &#39;C&#39; => &#39;C&#39;, &#39;D&#39; => &#39;D&#39;, &#39;E&#39; => &#39;E&#39;,
                 &#39;F&#39; => &#39;F&#39;, &#39;G&#39; => &#39;G&#39;, &#39;H&#39; => &#39;H&#39;, &#39;I&#39; => &#39;I&#39;, &#39;J&#39; => &#39;J&#39;,
                 &#39;K&#39; => &#39;K&#39;, &#39;L&#39; => &#39;L&#39;, &#39;M&#39; => &#39;M&#39;, &#39;N&#39; => &#39;N&#39;, &#39;O&#39; => &#39;O&#39;,
                 &#39;P&#39; => &#39;P&#39;, &#39;Q&#39; => &#39;Q&#39;, &#39;R&#39; => &#39;R&#39;, &#39;S&#39; => &#39;S&#39;, &#39;T&#39; => &#39;T&#39;,
                 &#39;U&#39; => &#39;U&#39;, &#39;V&#39; => &#39;V&#39;, &#39;W&#39; => &#39;W&#39;, &#39;X&#39; => &#39;X&#39;, &#39;Y&#39; => &#39;Y&#39;,
                 &#39;Z&#39; => &#39;Z&#39;, &#39;a&#39; => &#39;a&#39;, &#39;b&#39; => &#39;b&#39;, &#39;c&#39; => &#39;c&#39;, &#39;d&#39; => &#39;d&#39;,
                 &#39;e&#39; => &#39;e&#39;, &#39;f&#39; => &#39;f&#39;, &#39;g&#39; => &#39;g&#39;, &#39;h&#39; => &#39;h&#39;, &#39;i&#39; => &#39;i&#39;,
                 &#39;j&#39; => &#39;j&#39;, &#39;k&#39; => &#39;k&#39;, &#39;l&#39; => &#39;l&#39;, &#39;m&#39; => &#39;m&#39;, &#39;n&#39; => &#39;n&#39;,
                 &#39;o&#39; => &#39;o&#39;, &#39;p&#39; => &#39;p&#39;, &#39;q&#39; => &#39;q&#39;, &#39;r&#39; => &#39;r&#39;, &#39;s&#39; => &#39;s&#39;,
                 &#39;t&#39; => &#39;t&#39;, &#39;u&#39; => &#39;u&#39;, &#39;v&#39; => &#39;v&#39;, &#39;w&#39; => &#39;w&#39;, &#39;x&#39; => &#39;x&#39;,
                 &#39;y&#39; => &#39;y&#39;, &#39;z&#39; => &#39;z&#39;,
                 &#39;(&#39; => &#39;(&#39;, &#39;)&#39; => &#39;)&#39;, &#39;〔&#39; => &#39;[&#39;, &#39;〕&#39; => &#39;]&#39;, &#39;【&#39; => &#39;[&#39;,
                 &#39;】&#39; => &#39;]&#39;, &#39;〖&#39; => &#39;[&#39;, &#39;〗&#39; => &#39;]&#39;, &#39;“&#39; => &#39;[&#39;, &#39;”&#39; => &#39;]&#39;,
                 &#39;‘&#39; => &#39;[&#39;, &#39;’&#39; => &#39;]&#39;, &#39;{&#39; => &#39;{&#39;, &#39;}&#39; => &#39;}&#39;, &#39;《&#39; => &#39;<&#39;,
                 &#39;》&#39; => &#39;>&#39;,
                 &#39;%&#39; => &#39;%&#39;, &#39;+&#39; => &#39;+&#39;, &#39;—&#39; => &#39;-&#39;, &#39;-&#39; => &#39;-&#39;, &#39;~&#39; => &#39;-&#39;,
                 &#39;:&#39; => &#39;:&#39;, &#39;。&#39; => &#39;.&#39;, &#39;、&#39; => &#39;,&#39;, &#39;,&#39; => &#39;.&#39;, &#39;、&#39; => &#39;.&#39;,
                 &#39;;&#39; => &#39;,&#39;, &#39;?&#39; => &#39;?&#39;, &#39;!&#39; => &#39;!&#39;, &#39;…&#39; => &#39;-&#39;, &#39;‖&#39; => &#39;|&#39;,
                 &#39;”&#39; => &#39;"&#39;, &#39;’&#39; => &#39;`&#39;, &#39;‘&#39; => &#39;`&#39;, &#39;|&#39; => &#39;|&#39;, &#39;〃&#39; => &#39;"&#39;,
                 &#39; &#39; => &#39; &#39;);
    	return	strtr($html,$arr);
  }
로그인 후 복사

推荐学习:《PHP视频教程

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP에서 문자를 ASCII 코드로 변환하는 방법 PHP에서 문자를 ASCII 코드로 변환하는 방법 Mar 03, 2023 pm 06:55 PM

PHP에서는 ord() 함수를 사용하여 문자를 ASCII 코드로 변환할 수 있습니다. 이 함수는 단일 문자 또는 문자열의 첫 번째 문자의 ASCII 값을 반환할 수 있으며 변환 결과는 정수 형식으로 표시됩니다. 구문 "ord(문자열)", 매개변수 "string"은 생략할 수 없으며 ASCII 값을 가져올 문자열(또는 단일 문자)입니다.

PHP 문자열에서 특정 문자를 공백으로 바꾸는 방법 PHP 문자열에서 특정 문자를 공백으로 바꾸는 방법 Mar 06, 2023 pm 06:39 PM

PHP 문자열에서 특정 문자를 널 문자로 바꾸는 방법에는 두 가지가 있습니다. 1. str_replace() 함수를 사용하여 지정된 문자를 널 문자로 바꾸려면 첫 번째 매개변수만 지정된 문자로 설정하면 됩니다. 두 번째 매개변수를 null 문자로 설정합니다. 구문 "str_replace("specified Character","", $str)" 2. 정규식과 함께 preg_replace() 함수를 사용하여 지정된 문자를 일치시키고 이를 null 문자로 바꿉니다. 구문 " preg_replace('/지정된 문자/', "",$str)".

PHP에서 문자열의 모든 대문자를 제거하는 방법 PHP에서 문자열의 모든 대문자를 제거하는 방법 Sep 26, 2022 pm 07:59 PM

두 가지 제거 방법: 1. preg_replace()를 사용하여 정규식을 실행하여 모든 대문자를 검색하고 이를 null 문자로 바꿉니다. 구문은 "preg_replace('/[A-Z]/','',$str)"입니다. 2. preg_filter()를 사용하여 정규식을 실행하여 모든 대문자를 검색하고 이를 빈 문자로 바꿉니다. 구문은 "preg_filter('/[A-Z]/','',$str)"입니다.

PHP 문자열에서 왼쪽 및 오른쪽 문자를 제거하는 방법 PHP 문자열에서 왼쪽 및 오른쪽 문자를 제거하는 방법 Mar 27, 2023 pm 03:29 PM

PHP는 웹 애플리케이션을 개발하는 데 자주 사용되는 형식화된 프로그래밍 언어입니다. 웹 개발 중에 문자열에서 특정 문자를 제거하거나 문자열에 숫자나 문자를 유지하는 등 문자열에 대한 다양한 작업을 수행해야 할 수 있습니다. 이 기사에서는 PHP에서 문자열의 왼쪽이나 오른쪽에 있는 특정 문자를 제거하는 방법에 중점을 둘 것입니다.

PHP 문자열에서 한자만 추출하는 방법 PHP 문자열에서 한자만 추출하는 방법 Sep 22, 2022 pm 07:44 PM

두 가지 방법: 1. 일반 필터 문자열과 함께 preg_match_all()을 사용합니다. 구문은 "preg_match_all("/[\x{4e00}-\x{9fff}]+/u","$str",$arr);"입니다. ;2. 문자열에서 중국어가 아닌 문자를 정기적으로 검색하여 preg_replace()를 사용하고 이를 빈 문자로 바꿉니다. 구문은 "preg_replace("/[^\x{4E00}-\x{9FFF}]+/u입니다. ",'',$str)".

PHP에서 문자열에 문자를 추가하는 것이 가능합니까? PHP에서 문자열에 문자를 추가하는 것이 가능합니까? Aug 19, 2022 pm 07:51 PM

PHP는 문자열에 문자를 추가할 수 있습니다. 두 가지 구현 방법: 1. 문자열 커넥터 "."를 사용하여 지정된 문자를 문자열의 시작 또는 끝에 연결합니다. 구문은 "지정된 문자. 문자열" 또는 "문자열. 지정된 문자"입니다. ) 함수는 문자열의 지정된 위치에 지정된 문자를 삽입합니다. 구문은 "substr_replace(string, 지정된 문자, 지정된 위치, 0)"입니다. 지정된 위치의 값은 0, 음수 또는 양수일 수 있습니다.

PHP에서 문자열에서 큰따옴표를 제거하는 방법 PHP에서 문자열에서 큰따옴표를 제거하는 방법 Mar 28, 2023 pm 04:54 PM

PHP는 매우 인기 있는 프로그래밍 언어이며 동적 웹 사이트를 구축하는 데 선호되는 도구 중 하나입니다. PHP 개발에서는 종종 문자열을 조작해야 하는 경우가 있는데, 일반적인 요구 사항 중 하나는 문자열에서 큰따옴표를 제거하는 것입니다. 이 기사에서는 PHP 문자열에서 큰따옴표를 제거하는 몇 가지 방법을 소개합니다.

PHP에서 문자열을 정렬하는 방법 PHP에서 문자열을 정렬하는 방법 Sep 08, 2022 pm 08:02 PM

구현 단계: 1. str_split() 함수를 사용하여 문자열을 문자 배열로 변환합니다. 구문은 "str_split(string)"입니다. 2. asort() 또는 arsort() 함수를 사용하여 문자 배열을 오름차순 또는 오름차순으로 정렬합니다. 내림차순, 구문 "asort(문자 배열)" 또는 "arsort(문자 배열)" 3. implode() 함수를 사용하여 정렬된 문자 배열을 다시 문자열로 변환합니다. 구문은 "implode(정렬된 문자 배열)"입니다. ".

See all articles