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

· 2016-08-05 (금) 14:36:53 · 14540

데모 - 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 

 

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

개발자팁

5,403건

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

+
분류 제목 글쓴이 날짜 조회
PHP 16-10-10 조회 3,833
PHP 16-10-10 조회 3,477
PHP 16-10-06 조회 3,471
PHP 16-10-06 조회 4,707
PHP 16-10-06 조회 3,591
PHP 16-09-28 조회 3,514
jQuery 16-09-28 조회 4,648
PHP 16-09-27 조회 3,297
PHP 16-09-27 조회 4,531
웹서버 16-09-27 조회 3,547
JavaScript 16-09-23 조회 4,169
기타 16-09-20 조회 4,925
PHP 16-09-20 조회 4,305
기타 16-09-19 조회 5,412
JavaScript 16-09-17 조회 3,653
웹서버 16-09-15 조회 3,459
기타 16-09-01 조회 3,947
JavaScript 16-08-30 조회 3,507
node.js 16-08-23 조회 4,233
jQuery 16-08-21 조회 3,877
JavaScript 16-08-18 조회 5,444
PHP 16-08-11 조회 3,625
PHP 16-08-10 조회 4,046
JavaScript 16-08-09 조회 6,154
jQuery 16-08-05 조회 5,224
PHP 16-08-05 조회 1.5만
PHP 16-08-04 조회 7,250
jQuery 16-08-03 조회 3,859
PHP 16-08-03 조회 3,236
JavaScript 16-08-03 조회 6,423