Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

htmlspecialchars

(PHP 3, PHP 4, PHP 5)

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

Описание

string htmlspecialchars ( string string [, int quote_style [, string charset]] )

В HTML некоторые символы имеют специальное значение и для сохранения своего значения должны быть преобразованы в HTML сущности. Эта функция возвращает строку, над которой проведены некоторые из таких преобразований. Этих преобразований достаточно для большинства задач веб-программирования. Если вам нужно преобразовать все возможные сущности, используйте htmlentities().

Эта функция полезна при отображении данных, введенных пользователем, которые могут содержать нежелательные HTML тэги, например в форуме или гостевой книге. Необязательный второй аргумент quote_style определяет режим обработки одиночных и двойных кавычек. В режиме по умолчанию, ENT_COMPAT, преобразуются двойные кавычки, одиночные остаются без изменений. В режиме ENT_QUOTES преобразуются и двойные, и одиночные кавычки. а в режиме ENT_NOQUOTES и двойные, и одиночные кавычки остаются без изменений.

Производятся следующие преобразования:

  • '&' (амперсанд) преобразуется в '&'

  • '"' (двойная кавычка) преобразуется в '"' when ENT_NOQUOTES is not set.

  • ''' (одиночная кавычка) преобразуется в ''' только в режиме ENT_QUOTES.

  • '<' (знак "меньше чем") преобразуется в '&lt;'

  • '>' (знак "больше чем") преобразуется в '&gt;'

Пример 1. Пример использования htmlspecialchars()

<?php
$new
= htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo
$new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Обратите внимание, что функция не производит других преобразований кроме описанных выше. Для преобразования всех HTML сущностей используйте htmlentities(). Поддержка необязательного второго аргумента была добавлена в PHP 3.0.17 и PHP 4.0.3.

Необязательный третий аргумент charset определяет кодировку, используемую при преобразовании. По умолчанию используется кодировка ISO-8859-1. Поддержка этого аргумента была добавлена в PHP 4.1.0.

Начиная с PHP 4.3.0 поддерживаются следующие кодировки.

Таблица 1. Поддерживаемые кодировки

КодировкаПсевдонимыОписание
ISO-8859-1ISO8859-1 Западно-европейская Latin-1
ISO-8859-15ISO8859-15 Западно-европейская Latin-9. Добавляет знак евро, французские и финские буквы к кодировке Latin-1(ISO-8859-1).
UTF-8  8-битная Unicode, совместимая с ASCII.
cp866ibm866, 866 Кириллическая кодировка, применяемая в DOS. Поддерживается в версии 4.3.2.
cp1251Windows-1251, win-1251, 1251 Кириллическая кодировка, применяемая в Windows. Поддерживается в версии 4.3.2.
cp1252Windows-1252, 1252 Западно-европейская кодировка, применяемая в Windows.
KOI8-Rkoi8-ru, koi8r Русская кодировка. Поддерживается в версии 4.3.2.
BIG5950 Традиционный китайский, применяется в основном на Тайване.
GB2312936 Упрощенный китайский, стандартная национальная кодировка.
BIG5-HKSCS  Расширенная Big5, применяемая в Гонг-Конге.
Shift_JISSJIS, 932 Японская кодировка.
EUC-JPEUCJP Японская кодировка.

Замечание: Не перечисленные выше кодировки не поддерживаются, и вместо них применяется ISO-8859-1.

См. также описание функций get_html_translation_table(), strip_tags(), htmlentities() и nl2br().



implode> <htmlspecialchars_decode
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
htmlspecialchars
drew at august-harper dot com
22-Aug-2007 09:21
:// Escapes strings to be included in javascript
:function jsspecialchars($s) {
:    return preg_replace('/([^ :!#$%@()*+,-.\x30-\x5b\x5d-\x7e])/e',
:        "'\\x'.(ord('\\1')<16? '0': '').dechex(ord('\\1'))",$s);
:}

This function DOES NOT produce correct output in PHP5. Any strings containing a ” will be improperly escaped to \x5c, when it should be \x22.

I am not very good with regular expressions, so this is my solution to the problem.
//this is a workaround for jsspecialchars!
function ord2($s) {
if (strlen($s) == 2) {
return ord(substr($s,1,1));
} else {
return ord($s);
}
}
function JS_SpecialChars($s) {
return preg_replace(’/([^ !#$%@()*+,.\x30\x5b\x5d-\x7e])/e’,
”’\\x’.(ord2(’\\1’)&lt;16? ‘0’: ’’).dechex(ord2(’\\1’))”,$s);
}

I am sure that there is a better solution, but I can’t figure one out. This approach will probably also fix any other characters that end up being improperly escaped.
solar-energy
16-Jun-2007 03:21
also see function "urlencode()", useful for passing text with ampersand and other special chars through url

(i.e. the text is encoded as if sent from form using GET method)

e.g.

<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>

produces

<a href='foo.php?text=foo%3F%26bar%21'>link</a>

and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!"
galvao at galvao dot eti dot br
19-May-2007 06:19
There's a tiny error on alex-0 at hotmail dot co dot uk example:

The line:

$new = htmlspecialchars($_POST[message], ENT_QUOTES);

Should be written as:

$new = htmlspecialchars($_POST['message'], ENT_QUOTES);

Regards,
terminatorul at gmail dot com
27-Apr-2007 10:04
To html-encode Unicode characters that may not be part of your document character set (given in the META tag of your page), and so can not be output directly into your document source, you need to use mb_encode_numericentity(). Pay attention to it's conversion map argument.
frank at codedor dot be
16-Jan-2007 01:25
If you seem to have a problem with rendering dynamic RSS files from a database - try using htmlspecialchars() or htmlentities() on the text you are rendering.

Since XML and RSS is very strict about what is allowed inside nodes, you need to make sure everything is "A-OK" according to XML standards ...

Especially if the database you're pulling data from is fi. Latin-Swedish encoding, which seems to be the standard setting for MySQL databases.
alex-0 at hotmail dot co dot uk
23-Dec-2006 01:09
You can also use variables.
This is handy when working with forms to clear out an malicious html

<?php
$new
= htmlspecialchars($_POST[message], ENT_QUOTES);
echo
$new;
?>
MacIsaac
12-Apr-2006 01:05
<?php

// Escapes strings to be included in javascript
function jsspecialchars($s) {
    return
preg_replace('/([^ !#$%@()*+,-.\x30-\x5b\x5d-\x7e])/e',
       
"'\\x'.(ord('\\1')<16? '0': '').dechex(ord('\\1'))",$s);
}

?>

<script>
var some_variable = '<?= jsspecialchars($_GET['some_variable']) ?>';
</script>
richard at mf2fm dot com
03-Mar-2006 01:06
I had a script which detected swearing and wanted to make sure that words such as 'f &uuml; c k' didn't slip through the system.

After using htmlentities(), the following line converts most extended alphabet characters back to the standard alphabet so you can spot such problems..

$text=eregi_replace("&([a-z])[a-z0-9]{3,};", "\\\\1", $text);

This changes, for example, '&uuml;' into 'u' and '&szlig' into 's'.  Sadly it also converts '&pound;' and '&para;' into 'p' so it's not perfect but does solve a lot of the problems
mikiwoz at yahoo dot co dot uk
06-Oct-2005 02:40
I am not sure, maybe I'm missing something, but I have found something interesting:
I've been working on a project, where I had to use htmlspecialchars (for opbvious reasons). I olso needed to de-code the encoded string. What I have done was almost a copy and paste from php.net:
$trans=get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
$trans=array_flip($trans);
$string=strtr($encoded, $trans);
(it looked a bit different in my code, but the idea is clear)
I couldn't get the apostrophe sign de-coded, and I needed it for the <A> tags. After an hour or so of debuging, I decided do print_r($trans). What I got was:
...
[&#39;] => '
...
BUT the apostrophe was encoded to $#039; -> note the zero.
I don't suppose it's a bug, but it definetely IS a potential pitfall, watch out for this one.
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br)
01-Sep-2005 06:16
Hello,

If you are getting trouble to SGDB write/read HTML data, try to use this:

<?php

//from html_entity_decode() manual page
function unhtmlentities ($string) {
  
$trans_tbl =get_html_translation_table (HTML_ENTITIES );
  
$trans_tbl =array_flip ($trans_tbl );
   return
strtr ($string ,$trans_tbl );
}

//read from db
$content = stripslashes (htmlspecialchars ($field['content']));

//write to db
$content = unhtmlentities (addslashes (trim ($_POST['content'])));

//make sure result of function get_magic_quotes_gpc () == 0, you can get strange slashes in your content adding slashes twice

//better to do this using addslashes
$content = (! get_magic_quotes_gpc ()) ? addslashes ($content) : $content;

?>
jspalletta at gmail dot com
12-Jul-2005 05:37
I have found that this regular expression is sufficient for making sure that existing character entities show after htmlspecialchars() replaces _all_ occurrences of & with the &amp; entity.

<?php
// Note: hsc is an abbreviation of htmlspecialchars
function hscFixed($str)
{
    return
preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($str));
}
?>

The only flaw I can think of is if you have text of the vein; "&[word];", that is not meant to be a character but rather uses the ampersand and semicolon in their traditional grammatical denotations.  However I think this is highly unlikely to occur (among other reasons, the fact that anyone with enough grammatical inclination to use them as such probably won't leave out the space between the ampersand and the word).
25-Jun-2005 08:44
You can't use htmlspecialchars to create RSS feeds, since it expands ampersands.You need to use something like this:
$content = preg_replace(array('/</', '/>/', '/"/'), array('&lt;', '&gt;', '&quot;'), $content);
palrich at gmail dot com
16-May-2005 01:29
To Alexander Nofftz and urbanheroes:
It's not an IE problem.  There is no &apos; in HTML.  So it's only a problem if someone else does render this as an apostraphe on an HTML page.
paul dot l at aon dot at
09-May-2005 09:50
function reverse_htmlentities($mixed)
{
    $htmltable = get_html_translation_table(HTML_ENTITIES);
    foreach($htmltable as $key => $value)
    {
        $mixed = ereg_replace(addslashes($value),$key,$mixed);
    }
    return $mixed;
}

this is my version of a reversed htmlentities function
thisiswherejunkgoes at gmail dot com
05-May-2005 10:06
If there're any n00bs out there looking for a way to ensure that no html/special chars are getting sent to their databases/put through forms/etc., this has been doing the trick for me (though being at least slightly n00bish, if this won't always work perhaps someone will ammend :-)

function checkforchars ($foo) {

  if ($foo === htmlspecialchars($foo)) {
        return "Valid entry.";
  } else {
        return "Invalid entry.";
  }

}
urbanheroes {at} gmail {dot} com
30-Apr-2005 11:32
In response to the note made by Alexander Nofftz on October 2004, &#39; is used instead of &apos; because IE unfortunately seems to have trouble with the latter.
gt at realvertex.com
28-Apr-2005 09:55
Here is the recursive version that works for both arrays and strings. Doesn't look as elegant as the other recursive versions, because of the input checks.

function HTML_ESC($_input = null, $_esc_keys = false)
{
    if ((null != $_input) && (is_array($_input)))
    {
        foreach($_input as $key => $value)
        {
            if($_esc_keys)
            {
                $_return[htmlspecialchars($key)] = HTML_ESC($value,$_esc_keys);
            }
            else
            {
                $_return[$key] = HTML_ESC($value);
            }
        }
        return $_return;
    }
    elseif(null != $_input)
    {
        return htmlspecialchars($_input);
    }
    else
    {
        return null;
    }
}
took
23-Apr-2005 09:14
The Algo from donwilson at gmail dot com to reverse the action of htmlspecialchars(), edited for germany:

function unhtmlspecialchars( $string )
{
  $string = str_replace ( '&amp;', '&', $string );
  $string = str_replace ( '&#039;', '\'', $string );
  $string = str_replace ( '&quot;', '"', $string );
  $string = str_replace ( '&lt;', '<', $string );
  $string = str_replace ( '&gt;', '>', $string );
  $string = str_replace ( '&uuml;', '
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571