< > 를 포함한 문장을 노출할 때 한글만 있을 때는 문제가 없었는데
< > 안에 영문이 있을 경우 브라우저에서 태그로 인식해 표시되지 않는 오류가 발견되었다.
"<example> <샘플> 입니다 "
라는 문장이 있을 경우 화면에는
"<샘플> 입니다."
만 표시되었다.
그래서, < > 기호가 있을 경우 태그인지 판단해서 아니라면 htmlspecialchars() 처리하는 함수를 개발했다.
소스는 아래와 같다.
<?
function escape_non_html_tags($html) {
//예외처리할 태그 리스트
$tagList = [
'a', 'b', 'i', 'u', 'strong', 'em', 'p', 'div', 'span', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li',
'table', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot', 'br', 'hr', 'input', 'form', 'label', 'button', 'select', 'option',
'textarea', 'script', 'style', 'link', 'meta', 'title', 'head', 'html', 'body', 'header', 'footer', 'nav', 'section',
'article', 'aside', 'figure', 'figcaption', 'blockquote', 'pre', 'code'
];
return preg_replace_callback(
// 태그 검출: 알파벳, 한글, 숫자, 특수 문자가 포함된 태그를 모두 포함
'/<([\/\w가-힣\s="\'\/:.;-]+)>/',
function ($matches) use ($tagList) {
// 태그 이름을 추출 (알파벳과 한글 포함)
$tag_name = strtolower(preg_replace('/<\/?([a-zA-Z가-힣0-9-]+).*/', '$1', $matches[0]));
// 표준 HTML 태그일 경우 그대로 반환, 아니면 htmlspecialchars로 변환
if (in_array($tag_name, $tagList)) {
return $matches[0]; // 표준 태그는 그대로 유지
} else {
// 표준 태그가 아니면 htmlspecialchars로 변환
return htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8');
}
},
$html
);
}
$input_html = "여기는 <태그>입니다. 하지만 <example>는 태그가 아닙니다. <b>굵은 글씨</b>도 있습니다.<a href='test'>click</a>";
$output_html = escape_non_html_tags($input_html);
echo $output_html;
?>
'기타' 카테고리의 다른 글
플스플러스 11월 월간게임 - ps plus (2) | 2024.11.01 |
---|---|
플스플러스 10월 월간게임 (14) | 2024.10.09 |
RESTful API란 무엇인가 (6) | 2024.09.11 |
[일산] 포레스트아우팅스 (3) | 2024.09.08 |
플스플러스 9월 월간게임 (8) | 2024.09.05 |