CakeFest 2024: The Official CakePHP Conference

htmlspecialchars_decode

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

htmlspecialchars_decode Преобразовывает специальные HTML-сущности обратно в символы

Описание

htmlspecialchars_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401): string

Функция, в противоположность функции htmlspecialchars(), преобразовывает специальные HTML-сущности обратно в символы.

Конвертируемые сущности: &, " (без флага ENT_NOQUOTES), ' (с флагом ENT_QUOTES), < и >.

Список параметров

string

Строка, которую требуется преобразовать.

flags

Битовая маска из следующих флагов, которые определяют, как обрабатывать кавычки какие типы документов использовать. Маска по умолчанию: ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

Доступные константы параметра flags
Имя константы Описание
ENT_COMPAT Преобразовывает двойные кавычки, одинарные кавычки не изменяются.
ENT_QUOTES Преобразовывает как двойные, так и одинарные кавычки.
ENT_NOQUOTES Оставляет без изменения как двойные, так и одинарные кавычки.
ENT_SUBSTITUTE Заменяет неправильные последовательности кодовых единиц символом замены Юникода вместо возврата пустой строки: U+FFFD для строк в кодировке UTF-8 и &#FFFD; для строк в других кодировках.
ENT_HTML401 Обрабатывает код по правилам стандарта HTML 4.01.
ENT_XML1 Обрабатывает код по правилам стандарта XML 1.
ENT_XHTML Обрабатывает код по правилам стандарта XHTML.
ENT_HTML5 Обрабатывает код по правилам стандарта 5.

Возвращаемые значения

Функция возвращает декодированную строку.

Список изменений

Версия Описание
8.1.0 Значение по умолчанию для параметра flags изменили с ENT_COMPAT на ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

Примеры

Пример #1 Пример использования функции htmlspecialchars_decode()

<?php

$str
= "<p>this -&gt; &quot;</p>\n";

echo
htmlspecialchars_decode($str);

// Обратите внимание, что здесь кавычка не преобразовывается
echo htmlspecialchars_decode($str, ENT_NOQUOTES);

?>

Результат выполнения приведённого примера:

<p>this -> "</p>
<p>this -> &quot;</p>

Смотрите также

  • htmlspecialchars() - Преобразовывает специальные символы в HTML-сущности
  • html_entity_decode() - Преобразовывает HTML-сущности в символы
  • get_html_translation_table() - Возвращает таблицу преобразований, используемую функциями htmlspecialchars и htmlentities

add a note

User Contributed Notes 8 notes

up
2
Anonymous
17 years ago
This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

<?php

if ( !function_exists('htmlspecialchars_decode') )
{
function
htmlspecialchars_decode($text)
{
return
strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}
}

?>
up
1
thomas at xci[ignore_this]teit dot commm
16 years ago
The example for "htmlspecialchars_decode()" below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
"get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities()."

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

Proof:
Code:
--------------------
<?php
var_dump
(get_html_translation_table(HTML_SPECIALCHARS,ENT_QUOTES));
var_dump(htmlspecialchars('\'',ENT_QUOTES));
?>
--------------------

Output:
--------------------
array
'"' => '&quot;'
''' => '&#39;'
'<' => '&lt;'
'>' => '&gt;'
'&' => '&amp;'

'&#039;'
--------------------

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

<?php
function htmlspecialchars_decode($string,$style=ENT_COMPAT)
{
$translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
if(
$style === ENT_QUOTES){ $translation['&#039;'] = '\''; }
return
strtr($string,$translation);
}
?>

Br, Thomas
up
-2
or-k at or-k dot com
18 years ago
that works also with &auml; and &quot; and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
{
return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
}
up
-6
pinkgothic at gmail dot com
13 years ago
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code.

Why?

Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script:

<?php
$var
= "&amp;<script>alert('XSS');</script>";
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo
$var;
?>

Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS.

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.
up
-10
geoffers@gmail
18 years ago
[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

<?php

function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
return
strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}

?>
up
-12
benharold at mac dot com
15 years ago
If you use `htmlspecialchars()` to change things like the ampersand (&) into it's HTML equivalent (&amp;), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; "&amp;". Clearly nobody want's "&amp;" on his or her web page where there is supposed to be just an ampersand. Here's a quick and easy trick to make sure this doesn't happen:

<?php

$var
= "This is a string that could be passed to htmlspecialchars multiple times.";

if (
htmlspecialchars_decode($var) == $var) {
$var = htmlspecialchars($var);
}

echo
$var;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own.
up
-12
benharold at mac dot com
15 years ago
or of course:

<?php

$var
= "Blue & yellow make green.";

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo
$var; // outputs Blue &amp; yellow make green.

// you can do it a bunch of times, it still won't screw you!

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo
$var; // still outputs Blue &amp; yellow make green.

?>

Put it in a function. Add it to the method of some abstract data class.
up
-12
geoffers at gmail dot com
18 years ago
For PHP4 Compatibility:

<?php

function htmlspecialchars_decode_php4 ($str) {
return
strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}

?>
To Top