관리 메뉴

웹개발자의 기지개

[PHP] 모든 태그 필터링(제거) 사용자 정의 함수 만들기 본문

PHP

[PHP] 모든 태그 필터링(제거) 사용자 정의 함수 만들기

웹개발자 워니 2025. 10. 3. 18:46

일반 태그를 필터링하는 함수를 정리한다.

특히 아이폰의 경우 복사 / 붙여넣기 하면 Unicode 라는 눈에 보이지 않는 문자들도 같이 붙여지니 이부분도 필터링하도록 만들었다.

 

 

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
35
36
37
38
39
40
41
42
43
<?
function strip_all_tags_no_breaks($html) {
    if (is_null($html)) return '';
 
    // 1) script, style, noscript 제거
    $html = preg_replace(
        '/<(script|style|noscript)[^>]*>.*?<\/\1>/is',
        '',
        $html
    );
 
    // 2) HTML 태그 제거
    $text = strip_tags($html);
 
    // 3) HTML 엔티티 디코딩 (PHP5 기본 함수)
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
 
    // 4) &nbsp; → 일반 공백
    $text = str_replace("\xC2\xA0"' '$text);
 
    // 5) 개행, 탭, 캐리지리턴 제거 → 공백으로 치환
    $text = str_replace(array("\r\n""\r""\n""\t"), ' '$text);
 
    // 6) 연속된 공백 1칸으로 줄이기
    $text = preg_replace('/ {2,}/'' '$text);
    
    
    // 7) x-apple-data-detectors 관련 잔여 속성 제거 (혹시 남는 경우)
    $text = preg_replace('/x-apple-data-detectors="[^"]*"/i'''$text);
    $text = preg_replace('/class="[^"]*"/i'''$text);
    $text = preg_replace('/style="[^"]*"/i'''$text);
 
    // 8) 제어문자(Unicode bidi control) 제거
    $text = preg_replace('/[\x{202A}-\x{202E}\x{2066}-\x{2069}]/u'''$text);    
    
    
 
    // 9) 앞뒤 공백 제거
    $text = trim($text);
 
    return $text;
}
?>
cs

 

 

Comments