Função PHP htmlentities()

Exemplo

Convert characters to HTML entities:

<?php
$str = "<? W3S?h????>";
echo htmlentities($str);
?>

A saída HTML do código acima é a seguinte (ver código-fonte):

<!DOCTYPE html>
<html>
<body>
<© W3Sçh°°¦§>
</body>
</html>

A saída do navegador do código acima é:

<? W3S?h????>

Definição e uso

a função htmlentities() para converter caracteres em entidades HTML.

Dica:Para converter entidades HTML em caracteres, use html_entity_decode() função.

Dica:Use get_html_translation_table() Função para retornar a tabela de tradução usada pelo htmlentities().

Sintaxe

htmlentities(string,flags,character-set,double_encode)
Parâmetros Descrição
string Obrigatório. Define a string a ser convertida.
flags

Opcional. Define como os sinais de citação, codificações inválidas e o tipo de documento devem ser tratados.

Tipos de aspas disponíveis:

  • ENT_COMPAT - Padrão. Codificar apenas aspas duplas.
  • ENT_QUOTES - Codificar aspas duplas e simples.
  • ENT_NOQUOTES - Não codificar nenhuma aspas.

Codificações inválidas:

  • ENT_IGNORE - Ignorar codificações inválidas, em vez de retornar uma string vazia. Deve ser evitado, pois pode ter impacto na segurança.
  • ENT_SUBSTITUTE - Substituir codificações inválidas por um caractere especificado que contém um caractere de substituição Unicode U+FFFD (UTF-8) ou &#FFFD;, em vez de retornar uma string vazia.
  • ENT_DISALLOWED - Substituir os pontos de código inválidos no tipo de documento especificado por um caractere de substituição Unicode U+FFFD (UTF-8) ou &#FFFD;.

Flags adicionais para o tipo de documento usado:

  • ENT_HTML401 - Padrão. Tratar código como HTML 4.01.
  • ENT_HTML5 - Tratar código como HTML 5.
  • ENT_XML1 - Tratar código como XML 1.
  • ENT_XHTML - Tratar código como XHTML.
character-set

Opcional. Uma string que define o conjunto de caracteres a ser usado.

Allowed values:

  • UTF-8 - Default. ASCII compatible 8-bit Unicode with multi-byte
  • ISO-8859-1 - Western Europe
  • ISO-8859-15 - Western Europe (added euro sign + missing French and Finnish letters in ISO-8859-1)
  • cp866 - Cyrillic character set for DOS
  • cp1251 - Cyrillic character set for Windows
  • cp1252 - Western European character set for Windows
  • KOI8-R - Russian
  • BIG5 - Traditional Chinese, mainly used in Taiwan
  • GB2312 - Simplified Chinese, national standard character set
  • BIG5-HKSCS - Big5 with Hong Kong extension
  • Shift_JIS - Japanese
  • EUC-JP - Japanese
  • MacRoman - Character set used by the Mac operating system

Note:In versions of PHP before 5.4, unrecognized character sets are ignored and replaced by ISO-8859-1. Starting from PHP 5.4, unrecognized character sets are ignored and replaced by UTF-8.

double_encode

Optional. Boolean value, specifies whether to encode existing HTML entities.

  • TRUE - Default. Converts each entity.
  • FALSE - Will not encode existing HTML entities.

Technical details

Return value:

Return the converted string.

If string If the string contains invalid encoding, an empty string is returned unless ENT_IGNORE or ENT_SUBSTITUTE flags are set.

PHP version: 4+
Update log:

In PHP 5,character-set The default value of the parameter is changed to UTF-8.

In PHP 5.4, new features were added: ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_HTML5, ENT_XML1 and ENT_XHTML.

In PHP 5.3, a new feature was added: ENT_IGNORE.

In PHP 5.2.3, a new feature was added: double_encode Parameters.

In PHP 4.1, a new feature was added: character-set Parameters.

More examples

Example 1

Convert characters to HTML entities:

<?php
$str = "Bill & 'Steve'";
echo htmlentities($str, ENT_COMPAT); // Convert double quotes only
echo "<br>";
echo htmlentities($str, ENT_QUOTES); // Convert double quotes and single quotes
echo "<br>";
echo htmlentities($str, ENT_NOQUOTES); // Não converte nenhuma aspa
?>

A saída HTML do código acima é a seguinte (ver código-fonte):

<!DOCTYPE html>
<html>
<body>
Bill & 'Steve'<br>
Bill & 'Tarzan'<br>
Bill & 'Steve'
</body>
</html>

A saída do navegador do código acima é:

Bill & 'Steve'
Bill & 'Steve'
Bill & 'Steve'

Executar Exemplo

Exemplo 2

Ao usar o conjunto de caracteres Europeu Ocidental, converte alguns caracteres para entidades HTML:

<?php
$str = "Meu nome é Øyvind Øsane. Sou Norueguês.";
echo htmlentities($str, ENT_QUOTES, "ISO-8859-1"); 
//Converterá apenas aspas duplas (não aspas simples), e usa o conjunto de caracteres Europeu Ocidental
?>

A saída HTML do código acima é a seguinte (ver código-fonte):

<!DOCTYPE html>
<html>
<body>
Meu nome é Øyvind Øsane. Sou Norueguês.
</body>
</html>

A saída do navegador do código acima é:

Meu nome é Øyvind Øsane. Sou Norueguês.

Executar Exemplo