PHP htmlspecialchars() 함수
예시
미리 정의된 문자 "<"(보다 작음) 및 ">"(보다 큼)를 HTML 엔터티로 변환합니다.
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
위 코드의 HTML 출력은 (소스 보기):
<!DOCTYPE html>
<html>
<body>
This is some <b>bold</b> text.
</body>
</html>
위 코드의 브라우저 출력은 다음과 같습니다.
This is some <b>bold</b> text.
정의 및 사용
htmlspecialchars() 함수는 미리 정의된 일부 문자를 HTML 엔터티로 변환합니다.
미리 정의된 문자는 다음과 같습니다.
- &(앰퍼샌드)는 &
- "(큰따옴표)는 "
- '(작은따옴표)는 '
- <(보다 작음)은 <
- >(보다 큼)은 >
팁: 특수 HTML 엔티티를 다시 문자로 변환하려면 htmlspecialchars_decode() 함수를 사용하십시오.
통사론
htmlspecialchars(string,flags,character-set,double_encode)
매개변수 값
Parameter | Description |
---|---|
string | Required. Specifies the string to convert |
flags | Optional. Specifies how to handle quotes, invalid encoding and the used document type. The available quote styles are:
Invalid encoding:
Additional flags for specifying the used doctype:
|
character-set | Optional. A string that specifies which character-set to use. Allowed values are:
Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8. |
double_encode | Optional. A boolean value that specifies whether to encode existing html entities or not.
|
기술적 세부 사항
반환 값: | 변환된 문자열을 반환합니다 . 문자열 에 잘못된 인코딩이 포함되어 있으면 ENT_IGNORE 또는 ENT_SUBSTITUTE 플래그가 설정되지 않은 한 빈 문자열을 반환합니다. |
---|---|
PHP 버전: | 4+ |
변경 로그: | PHP 5.6 - 문자 집합
매개변수의 기본값을 기본 문자 집합의 값으로 변경했습니다(구성에서). PHP 5.4 - 문자 집합 매개변수 의 기본값 을 UTF-8로 변경했습니다. PHP 5.4 - ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_HTML5, ENT_XML1 및 ENT_XHTML 추가 PHP 5.3 - ENT_IGNORE 상수 추가. PHP 5.2.3 - double_encode 매개변수를 추가했습니다. PHP 4.1 - 문자 집합 매개변수를 추가했습니다. |
더 많은 예
예시
미리 정의된 일부 문자를 HTML 엔터티로 변환:
<?php
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
?>
위 코드의 HTML 출력은 (소스 보기):
<!DOCTYPE html>
<html>
<body>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
</body>
</html>
위 코드의 브라우저 출력은 다음과 같습니다.
Jane & 'Tarzan'
Jane & 'Tarzan'
Jane & 'Tarzan'
예시
큰따옴표를 HTML 엔터티로 변환:
<?php
$str = 'I love "PHP".';
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
?>
위 코드의 HTML 출력은 (소스 보기):
<!DOCTYPE html>
<html>
<body>
I love "PHP".
</body>
</html>
위 코드의 브라우저 출력은 다음과 같습니다.
I love "PHP".
❮ PHP 문자열 참조