728x90

HTML(Hyper Text Markup Language)은 태그로 구성되어 있다.
- HTML 태그는 기본적으로 '<' 기호로 시작하여 '>'로 끝난다.
- 브라우저에서 HTML을 파싱할 때는 꺽쇠기호 <> 를 HTML 태그의 시작과 끝으로 인식 할 수 있다
- 따옴표 " "는 HTML 속성의 값이 시작되거나 끝난 것으로 인식할 수 있다.
- & 기호는 Entity 기호의 시작으로 오인될 수 있다.

HTML 에서 special character 를 나타내는 방법은 두가지가 있다.
Numeric HTML entity, Symbolic HTML entity 다.
http://entitycode.com/ 에 가면 주요 특수문자을 찾을 수 있다.
http://dmobi.tistory.com/72 에도 많은 특수문자를 참조할 수 있다.

"<", ">", "&" 이런 기호들을 Web 브라우저에서 제대로 표현하려면 &lt; &gt; &amp; 로 변환해주어야 한다.

PHP에서는
htmlspecialchars() HTML에서 사용하는 특수문자를 변경해주는 역할을 한다.


stripslashes()는 따옴표에 붙는 백슬래시를 제거해주는 함수다.
따옴표에 백슬래시를 붙여주는 함수는 addslashes() 다.
HTML 코드를 DB에 저장할 때 따옴표나 여러 특수문자 때문에 에러를 발생하기도 한다
DB에 저장할 때는 특수문자를 적절하게 변경해주어야 한다.


PHP에서 HTML 구문을 그대로 출력하기 위해 htmlspecialchars를 사용하여 인코딩된 문자열을  DB에 넣어준다.
반대로 DB에 있는 값을 불러와 HTML 소스로 변환할 때는 일반적으로 htmlspecialchars_decode를 많이 사용한다.
그런데 이 함수를 사용하는데 문제가 있다. htmlspecialchars_decode는 &nbsp;를 공백으로 다시 되돌려 주지 않는다.


&nbsp;와 같은 것은 html_entity_decode를 사용하면 된다.
이 함수는 htmlentities와 대응되는 함수이다.

htmlspecialchars와 htmlentities는 유사하나 htmlentities가 더 많은 문자를 변환한다.
htmlspecialchars_decode와 html_entity_decode는 유사하나 html_entity_decode가 더 많은 문자를 되돌린다.


$str = "I'll \"walk\" the <b>dog</b> now.\n";

$str_encode = htmlentities($str);
echo $str_encode; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now.

$str_decode = html_entity_decode($str_encode);
echo $str_decode; // I'll "walk" the <b>dog</b> now.


$str = "<a href=\"https://www.w3schools.com\">w3schools.com</a>\n";
$str_encode = htmlentities($str);
echo $str_encode; // &lt;a href=&quot;https://www.w3schools.com&quot;&gt;w3schools.com&lt;/a&gt;

$str_decode = html_entity_decode($str_encode);
echo $str_decode; //  



PHP 버전이 낮은 경우에는 get_magic_quotes_gpc()함수로 magic_quotes 값을 확인 후 써야 한다.
그렇지 않으면 불필요한 백슬래시까지 데이터로 처리하는 경우가 발생하기 때문이다.
Returns 0 if magic_quotes_gpc is off, 1 otherwise.
PHP 5.4.0. always returns FALSE because the magic quotes feature was removed from PHP.

if ( get_magic_quotes_gpc() ) {
    $str = htmlspecialchars( stripslashes( $str) ) ;
}else{
    $str = htmlspecialchars( $str) ;
}

// Usage across all PHP versions
if (get_magic_quotes_gpc()) {
    $lastname = stripslashes($_POST['name']);
}
else {
    $lastname = $_POST['name'];
}

문자 치환이 필요한 경우
- DB와 연동하기 위해 특수문자 또는 줄바꿈 처리시
- 게시판에서 특정 문자의 제거 또는 치환으로 특수문자와 줄바꿈 변경에 자주 사용

블로그 이미지

Link2Me

,