얕고넓은지식/linux

php7 preg_replace 함수를 이용한 정규식 태그 필터링

쪽마 2021. 4. 12. 21:05
반응형


iframe 제거
$STRING=preg_replace("!<iframe(.*?)<\/iframe>!is","",$STRING);

script 제거
$STRING=preg_replace("!<script(.*?)<\/script>!is","",$STRING);

meta 제거
$STRING=preg_replace("!<meta(.*?)>!is","",$STRING);

style 태그 제거
$STRING=preg_replace("!<style(.*?)<\/style>!is","",$STRING);

&nbsp;를 공백으로 변환
$STRING=str_replace("&nbsp;"," ",$STRING);

연속된 공백 1개로
$STRING=preg_replace("/\s{2,}/"," ",$STRING);

태그안에 style= 속성 제거
$STRING=preg_replace("/ style=([^\"\']+) /"," ",$STRING); // style=border:0... 따옴표가 없을때
$STRING=preg_replace("/ style=(\"|\')?([^\"\']+)(\"|\')?/","",$STRING); // style="border:0..." 따옴표 있을때

태그안의 width=, height= 속성 제거
$STRING=preg_replace("/ width=(\"|\')?\d+(\"|\')?/","",$STRING);
$STRING=preg_replace("/ height=(\"|\')?\d+(\"|\')?/","",$STRING);

img 태그 추출 src 추출
preg_match("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT);
preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT);

호스트 추출
<?
preg_match("/^(http:\/\/)?([^\/]+)/i","http://www.naver.com/index.html",$matches);
$host = $matches[2];
echo$matches[0]."<br>";
echo$matches[1]."<br>";
echo$matches[2]."<br>";
?>



해당 소스는 preg_replace, preg_match,  preg_match_all 함수를 사용하였으며 PHP4, PHP5, PHP7에서 사용할 수 있습니다. 보안에 문제가되는 iframe, script, style 과 같은 함수는 글 제목이나 내용에서 필수적으로 삭제하는 게 좋습니다.

//iframe 제거 
$STRING = preg_replace("!<iframe(.*?)<\/iframe>!is","",$STRING);

//script 제거 
$STRING = preg_replace("!<script(.*?)<\/script>!is","",$STRING);

//meta 제거 
$STRING = preg_replace("!<meta(.*?)>!is","",$STRING); 

//style 태그 제거  
$STRING = preg_replace("!<style(.*?)<\/style>!is","",$STRING); 

//&nbsp;를 공백으로 변환 
$STRING = str_replace("&nbsp;"," ",$STRING);

//연속된 공백 1개로 
$STRING = preg_replace("/\s{2,}/"," ",$STRING); 

//태그안에 style= 속성 제거 
$STRING = preg_replace("/ style=([^\"\']+) /"," ",$STRING); // style=border:0... 따옴표가 없을때 
$STRING = preg_replace("/ style=(\"|\')?([^\"\']+)(\"|\')?/","",$STRING); // style="border:0..." 따옴표 있을때

//태그안의 width=, height= 속성 제거 
$STRING = preg_replace("/ width=(\"|\')?\d+(\"|\')?/","",$STRING); 
$STRING = preg_replace("/ height=(\"|\')?\d+(\"|\')?/","",$STRING);

//img 태그 추출 src 추출 
preg_match("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT); 
preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$STRING,$RESULT);

 

간단한 팁

사이트 제목이나 성명, 이메일 등 특정 스크립트를 사용하지 못하게 하는 경우에는 간단한 치환만으로도 보안 문제를 해결 할 수 있습니다. HTMLSPECIALCHARS 함수도 문자열에서 특정한 특수문자를 HTML 엔티티로 변환해주는 동일한 기능으로 볼 수 있습니다. 

$_POST["name"] = STR_REPLACE("<","&lt;",$_POST["name"]);
$_POST["name"] = STR_REPLACE(">","&gt;",$_POST["name"]);
특수문자 변환된 문자
& (엔퍼샌트) &amp;
"" (겹 따옴표) &quot;
'' (홑 따옴표) &#039;
< (적다) &lt;
> (크다) &gt;

 

반응형