📖
PHP 정규식을 활용한 태그 및 특정 문자열 제거 및 추출 방법
페이지 정보
본문
php에서 정규식을 활용하여 문자열안에 있는 태그 제거 및 추출 방법에 대해서 알아보겠습니다.
정규식을 잘 활용하면 소스가 간결해지며 그만큼 좋은 효과를 가져올수 있다고 하는데요 이걸 또 평소에 쓰는 버릇을 해야하는데
자주 쓰이진 않다보니 금방 까먹게 되네요.
TEXTAREA 제거[code]$content = preg_replace("!<TEXTAREA(.*?)>!is","[TEXTAREA]",$content);
$content = preg_replace("!</TEXTAREA(.*?)>!is","[/TEXTAREA]",$content);[/code]
script 제거[code]$str=preg_replace("!<script(.*?)<\/script>!is","",$str);[/code]
iframe 제거[code]$str=preg_replace("!<iframe(.*?)<\/iframe>!is","",$str);[/code]
meta 제거[code]$str=preg_replace("!<meta(.*?)>!is","",$str);[/code]
style 태그 제거[code]$str=preg_replace("!<style(.*?)<\/style>!is","",$str);[/code]
공백공백 을 공백으로 변환[code]$str=str_replace(" "," ",$str);[/code]
연속된 공백 1개로[code]$str=preg_replace("/\s{2,}/"," ",$str);[/code]
태그안에 style= 속성 제거[code]$str=preg_replace("/ zzstyle=([^\"']+) /"," ",$str); // style=border:0... 따옴표가 없을때
$str=preg_replace("/ style=(\"|')?([^\"']+)(\"|')?/","",$str); // style="border:0..." 따옴표 있을때[/code]
태그안의 width=, height= 속성 제거[code]$str=preg_replace("/ width=(\"|')?\d+(\"|')?/","",$str);
$str=preg_replace("/ height=(\"|')?\d+(\"|')?/","",$str);[/code]
img 태그 추출 src 추출[code]preg_match("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$str,$RESULT);
preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$str,$RESULT);[/code]
호스트 추출[code]<?
preg_match("/^(http:\/\/)?([^\/]+)/i","http://www.naver.com/index.php",$matches);
$host = $matches[2];
echo$matches[0]."<br>";
echo$matches[1]."<br>";
echo$matches[2]."<br>";
?>[/code]
정규식을 잘 활용하면 소스가 간결해지며 그만큼 좋은 효과를 가져올수 있다고 하는데요 이걸 또 평소에 쓰는 버릇을 해야하는데
자주 쓰이진 않다보니 금방 까먹게 되네요.
TEXTAREA 제거[code]$content = preg_replace("!<TEXTAREA(.*?)>!is","[TEXTAREA]",$content);
$content = preg_replace("!</TEXTAREA(.*?)>!is","[/TEXTAREA]",$content);[/code]
script 제거[code]$str=preg_replace("!<script(.*?)<\/script>!is","",$str);[/code]
iframe 제거[code]$str=preg_replace("!<iframe(.*?)<\/iframe>!is","",$str);[/code]
meta 제거[code]$str=preg_replace("!<meta(.*?)>!is","",$str);[/code]
style 태그 제거[code]$str=preg_replace("!<style(.*?)<\/style>!is","",$str);[/code]
공백공백 을 공백으로 변환[code]$str=str_replace(" "," ",$str);[/code]
연속된 공백 1개로[code]$str=preg_replace("/\s{2,}/"," ",$str);[/code]
태그안에 style= 속성 제거[code]$str=preg_replace("/ zzstyle=([^\"']+) /"," ",$str); // style=border:0... 따옴표가 없을때
$str=preg_replace("/ style=(\"|')?([^\"']+)(\"|')?/","",$str); // style="border:0..." 따옴표 있을때[/code]
태그안의 width=, height= 속성 제거[code]$str=preg_replace("/ width=(\"|')?\d+(\"|')?/","",$str);
$str=preg_replace("/ height=(\"|')?\d+(\"|')?/","",$str);[/code]
img 태그 추출 src 추출[code]preg_match("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$str,$RESULT);
preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$str,$RESULT);[/code]
호스트 추출[code]<?
preg_match("/^(http:\/\/)?([^\/]+)/i","http://www.naver.com/index.php",$matches);
$host = $matches[2];
echo$matches[0]."<br>";
echo$matches[1]."<br>";
echo$matches[2]."<br>";
?>[/code]
댓글목록
등록된 댓글이 없습니다.
![]() ![]() |