php preg_replace 함수를 이용한 정규식 태그 필터링 예제

· 9년 전 · 11568

데모 - http://demo.widgets.co.kr/?c=64/81/82

매뉴얼 - http://kr2.php.net/manual/kr/function.preg-replace.php



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);

 를 공백으로 변환

$STRING=str_replace(" "," ",$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>";

출력 - 
http://www.naver.com
http://
www.naver.com

데모 - http://demo.widgets.co.kr/?c=64/81/82 

 

|
댓글을 작성하시려면 로그인이 필요합니다.

개발자팁

개발과 관련된 유용한 정보를 공유하세요. 질문은 QA에서 해주시기 바랍니다.

+
분류 제목 글쓴이 날짜 조회
기타 9년 전 조회 4,368
PHP 9년 전 조회 3,885
기타 9년 전 조회 4,926
JavaScript 9년 전 조회 3,199
웹서버 9년 전 조회 3,067
기타 9년 전 조회 3,588
JavaScript 9년 전 조회 3,152
node.js 9년 전 조회 3,811
jQuery 9년 전 조회 3,498
JavaScript 9년 전 조회 5,100
PHP 9년 전 조회 3,223
PHP 9년 전 조회 3,651
JavaScript 9년 전 조회 5,746
jQuery 9년 전 조회 4,853
PHP 9년 전 조회 1.2만
PHP 9년 전 조회 6,807
jQuery 9년 전 조회 3,473
PHP 9년 전 조회 2,880
JavaScript 9년 전 조회 6,040
MySQL 9년 전 조회 1.1만
node.js 9년 전 조회 4,084
PHP 9년 전 조회 3,177
9년 전 조회 6,569
9년 전 조회 3,251
9년 전 조회 4,678
9년 전 조회 3,173
9년 전 조회 6,852
9년 전 조회 3,801
9년 전 조회 2,003
9년 전 조회 3,638